const cron = require('node-cron');
const moment = require('moment');
const { Bookings } = require('../models');
const { Op } = require('sequelize');
const { createNotification } = require('../helpers');

const notifyCheckIns = () => {
	cron.schedule('* * * * *', async () => {
		// runs every minute
		try {
			const today = moment().format('YYYY-MM-DD'); // today's date
			const startOfDay = `${today} 00:00:00`;
			const endOfDay = `${today} 23:59:59`;

			const checkInBookings = await Bookings.findAll({
				where: {
					check_in: {
						[Op.between]: [startOfDay, endOfDay],
					},
					status: {
						[Op.not]: 'Cancelled',
					},
				},
			});

			// save notifications for check-in bookings
			for (const booking of checkInBookings) {
				const message = `Guest is scheduled to check in today (${booking.check_in}).`;
				await createNotification(booking.host_id, booking.id, message, 'Check-In');
			}

			console.log(`Notifications for ${checkInBookings.length} check-ins saved.`);
		} catch (error) {
			console.error('Error running notifyCheckIns cron job:', error.message);
		}
	});
};

module.exports = notifyCheckIns;
