const { Op } = require("sequelize");
const dbSAPPS = require("../../helpers/db");

module.exports = {
	getClockReminderOptions,
};

/**
 * Check if a date is within Ramadan period
 * @param {String} startDate - Start date of Ramadan (YYYY-MM-DD)
 * @param {String} endDate - End date of Ramadan (YYYY-MM-DD)
 * @param {Date} checkDate - Date to check (default: today)
 * @returns {Boolean} - True if date is within Ramadan
 */
function isInRamadanPeriod(startDate, endDate, checkDate = new Date()) {
	if (!startDate || !endDate) return false;
	
	try {
		const start = new Date(startDate);
		const end = new Date(endDate);
		const check = new Date(checkDate);
		
		// Reset time portion for comparison
		start.setHours(0, 0, 0, 0);
		end.setHours(23, 59, 59, 999);
		check.setHours(0, 0, 0, 0);
		
		return check >= start && check <= end;
	} catch (error) {
		console.warn("Error checking Ramadan period:", error);
		return false;
	}
}

/**
 * Get effective shift times based on whether the date is in Ramadan
 * @param {Object} shiftType - ShiftType object
 * @param {Date} checkDate - Date to check
 * @returns {Object} - Effective times { startTime, endTime, lateTime, earlyTime, isRamadan }
 */
function getEffectiveShiftTimes(shiftType, checkDate = new Date()) {
	const isRamadan = isInRamadanPeriod(
		shiftType.start_date_ramadhan,
		shiftType.end_date_ramadhan,
		checkDate
	);
	
	// If Ramadan and Ramadan times are defined, use them
	if (isRamadan && shiftType.start_time_ramadhan) {
		return {
			startTime: shiftType.start_time_ramadhan,
			endTime: shiftType.end_time_ramadhan || shiftType.end_time,
			lateTime: shiftType.late_time_ramadhan || shiftType.late_time,
			earlyTime: shiftType.early_time_ramadhan || shiftType.early_time,
			isRamadan: true,
		};
	}
	
	// Otherwise use normal times
	return {
		startTime: shiftType.start_time,
		endTime: shiftType.end_time,
		lateTime: shiftType.late_time,
		earlyTime: shiftType.early_time,
		isRamadan: false,
	};
}

/**
 * Get shift types for clock reminder settings
 * Includes Ramadan period detection and effective times
 * 
 * @param {Object} params - Parameters
 * @param {number} params.company_id - Company ID
 * @param {string} [params.date] - Optional date (YYYY-MM-DD) for preview
 * @returns {Promise<Object>} - Shift types with Ramadan info
 */
async function getClockReminderOptions(params) {
	try {
		const { company_id, date } = params;
		
		if (!company_id) {
			return {
				success: false,
				message: "Company ID is required",
				options: [],
			};
		}

		// Use specified date or today
		const checkDate = date ? new Date(date) : new Date();
		
		// Get shift types for this company
		const shiftTypes = await dbSAPPS.ShiftType.findAll({
			where: {
				company_id: Number(company_id),
				enabled: true,
			},
			attributes: [
				"id",
				"name",
				"display_name",
				"code",
				"start_time",
				"end_time",
				"late_time",
				"early_time",
				// Ramadan fields
				"start_date_ramadhan",
				"end_date_ramadhan",
				"start_time_ramadhan",
				"end_time_ramadhan",
				"late_time_ramadhan",
				"early_time_ramadhan",
			],
			order: [["display_name", "ASC"]],
		});

		// Format the response with effective times
		const options = shiftTypes.map((shiftType) => {
			const effectiveTimes = getEffectiveShiftTimes(shiftType, checkDate);
			
			return {
				id: shiftType.id,
				name: shiftType.name,
				display_name: shiftType.display_name,
				code: shiftType.code,
				// Original times
				original: {
					start_time: shiftType.start_time,
					end_time: shiftType.end_time,
					late_time: shiftType.late_time,
					early_time: shiftType.early_time,
				},
				// Ramadan times (if defined)
				ramadan: shiftType.start_time_ramadhan ? {
					start_date_ramadhan: shiftType.start_date_ramadhan,
					end_date_ramadhan: shiftType.end_date_ramadhan,
					start_time_ramadhan: shiftType.start_time_ramadhan,
					end_time_ramadhan: shiftType.end_time_ramadhan,
					late_time_ramadhan: shiftType.late_time_ramadhan,
					early_time_ramadhan: shiftType.early_time_ramadhan,
				} : null,
				// Effective times (based on current date)
				effective: effectiveTimes,
				// Formatted display
				displayTime: `${effectiveTimes.startTime} - ${effectiveTimes.endTime}`,
				displayTimeWithLabel: effectiveTimes.isRamadan 
					? `${effectiveTimes.startTime} - ${effectiveTimes.endTime} (Ramadan)`
					: `${effectiveTimes.startTime} - ${effectiveTimes.endTime}`,
			};
		});

		// Determine which shift type should be auto-selected
		// Based on current time vs shift times
		const now = new Date();
		const currentTime = now.toTimeString().slice(0, 8); // HH:MM:SS
		
		let autoDetectedShiftTypeId = null;
		
		// Find the shift type that matches current time
		for (const option of options) {
			const startTime = option.effective.startTime;
			const endTime = option.effective.endTime;
			
			// Simple comparison - if current time is within the shift window
			if (currentTime >= startTime && currentTime <= endTime) {
				autoDetectedShiftTypeId = option.id;
				break;
			}
		}
		
		// If no match found, default to first shift type
		if (!autoDetectedShiftTypeId && options.length > 0) {
			autoDetectedShiftTypeId = options[0].id;
		}

		return {
			success: true,
			message: "Loaded successfully!",
			options: options,
			autoDetected: {
				shiftTypeId: autoDetectedShiftTypeId,
				date: checkDate.toISOString().slice(0, 10),
				isRamadan: options.find(o => o.id === autoDetectedShiftTypeId)?.effective?.isRamadan || false,
			},
		};
	} catch (error) {
		console.error("Error getting clock reminder options:", error);
		return {
			success: false,
			message: error?.message || "Failed to load shift types",
			options: [],
		};
	}
}
