const calculateNights = (start, end) => {
	const startDate = new Date(start);
	const endDate = new Date(end);
	const timeDiff = endDate - startDate; // difference in milliseconds
	return Math.ceil(timeDiff / (1000 * 60 * 60 * 24)); // convert to days
};

// start of day (00:00:00)
const setStartOfDay = (dateObj) => new Date(dateObj.setHours(0, 0, 0, 0));

// end of day (23:59:59)
const setEndOfDay = (dateObj) => new Date(dateObj.setHours(23, 59, 59, 999));

// get the date range based on the filter
const getDateRangeForFilter = (filter, selectedDate, selectedMonth, selectedYear, today) => {
	let startOfDay, endOfDay;

	switch (filter) {
		case 'date':
			if (selectedDate && !isNaN(selectedDate.getTime())) {
				startOfDay = setStartOfDay(new Date(selectedDate));
				endOfDay = setEndOfDay(new Date(selectedDate));
			} else {
				startOfDay = setStartOfDay(new Date(today));
				endOfDay = setEndOfDay(new Date(today));
			}
			return { startOfDay, endOfDay };

		case 'month':
			if (selectedMonth) {
				selectedDate = new Date(selectedYear, selectedMonth - 1, 1); // for 0-based month index
				startOfDay = setStartOfDay(selectedDate);
				const lastOfMonth = new Date(selectedYear, selectedMonth, 0); // last day of the month
				endOfDay = setEndOfDay(lastOfMonth);
			} else {
				startOfDay = setStartOfDay(new Date(today.getFullYear(), today.getMonth(), 1));
				endOfDay = setEndOfDay(new Date(today.getFullYear(), today.getMonth() + 1, 0));
			}
			return { startOfDay, endOfDay };

		case 'last_6_months':
			const sixMonthsAgo = new Date(today);
			sixMonthsAgo.setMonth(today.getMonth() - 6);
			return { startOfDay: sixMonthsAgo, endOfDay: today };

		case 'year':
			startOfDay = setStartOfDay(new Date(selectedYear, 0, 1)); // January 1st
			endOfDay = setEndOfDay(new Date(selectedYear, 11, 31)); // December 31st
			return { startOfDay, endOfDay };

		default:
			return { startOfDay: null, endOfDay: null }; // no filter, no date range
	}
};

module.exports = {
	calculateNights,
	setStartOfDay,
	setEndOfDay,
	getDateRangeForFilter,
};
