const { Op } = require('sequelize');
const { HotelBookings } = require('../models');

exports.calculateNights = (checkIn, checkOut) => {
	const inDate = new Date(checkIn);
	const outDate = new Date(checkOut);
	let nights = Math.round((outDate.getTime() - inDate.getTime()) / (1000 * 60 * 60 * 24));
	if (nights <= 0) nights = 1;
	return nights;
};

exports.getExistingBookings = async (roomId, checkIn, checkOut) => {
	let bookings = await HotelBookings.findOne({
		where: {
			hotel_room_id: roomId,
			[Op.or]: [
				{
					check_in: {
						[Op.between]: [checkIn, checkOut],
					},
				},
				{
					check_out: {
						[Op.between]: [checkIn, checkOut],
					},
				},
				{
					[Op.and]: [{ check_in: { [Op.lte]: checkIn } }, { check_out: { [Op.gte]: checkOut } }],
				},
			],
		},
	});

	return bookings;
};
