const { Op } = require('sequelize');

// bookings filter - host
function buildFilter(userId, { status, date, bookingDate, search }) {
	const filter = {
		host_id: userId,
	};

	if (status) {
		filter.status = status;
	}

	if (date) {
		const startOfDay = new Date(date);
		const endOfDay = new Date(startOfDay);
		endOfDay.setDate(startOfDay.getDate() + 1);

		filter.createdAt = {
			[Op.gte]: startOfDay,
			[Op.lt]: endOfDay,
		};
	}

	if (bookingDate) {
		filter.check_in = { [Op.lte]: new Date(bookingDate) };
		filter.check_out = { [Op.gte]: new Date(bookingDate) };
	}

	if (search) {
		filter[Op.or] = [
			{ booking_no: { [Op.like]: `%${search}%` } },
			{ '$customers.firstname$': { [Op.like]: `%${search}%` } },
			{ '$customers.lastname$': { [Op.like]: `%${search}%` } },
			{ '$listing.name$': { [Op.like]: `%${search}%` } },
		];
	}

	return filter;
}

module.exports = { buildFilter };
