/**
 * dateUtils.js - Date manipulation utility functions
 * 
 * This module contains utility functions for formatting and manipulating dates.
 */

/**
 * Format date as YYYY-MM-DD for API requests
 * @param {Date} date - Date object to format
 * @returns {string} Formatted date string
 */
export function formatDateForAPI(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
}

/**
 * Format date for display (DD/MM/YYYY)
 * @param {string} dateStr - Date string in YYYY-MM-DD format
 * @returns {string} Formatted date string for display
 */
export function formatDateForDisplay(dateStr) {
    if (!dateStr || !/\d{4}-\d{2}-\d{2}/.test(dateStr)) {
        // Return original string or an error/placeholder if format is unexpected
        console.warn(`Invalid dateStr format for formatDateForDisplay: ${dateStr}`);
        return dateStr; 
    }
    // Parse YYYY-MM-DD as local date to avoid timezone interpretation issues
    const parts = dateStr.split('-');
    const year = parseInt(parts[0], 10);
    const month = parseInt(parts[1], 10) - 1; // JavaScript months are 0-indexed
    const day = parseInt(parts[2], 10);
    const date = new Date(year, month, day);

    return date.toLocaleDateString('en-GB', {
        day: '2-digit',
        month: '2-digit',
        year: 'numeric'
    });
}

/**
 * Get days of the current week (Monday to Sunday)
 * @returns {Array} Array of day objects with date, dayName, and displayDate
 */
export function getDaysOfWeek() {
    const today = new Date();
    const currentDay = today.getDay(); // 0 is Sunday, 1 is Monday, ...
    const mondayOffset = currentDay === 0 ? -6 : 1 - currentDay; // Calculate days from today to Monday
    
    const days = [];
    const monday = new Date(today);
    monday.setDate(today.getDate() + mondayOffset);
    
    // Generate array with dates for Monday through Sunday
    for (let i = 0; i < 7; i++) {
        const date = new Date(monday);
        date.setDate(monday.getDate() + i);
        
        // Format date using local time
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        
        days.push({
            date: `${year}-${month}-${day}`, // YYYY-MM-DD format
            dayName: date.toLocaleDateString('en-US', { weekday: 'long' }), // Monday, Tuesday, etc.
            displayDate: date.toLocaleDateString('en-GB') // DD/MM/YYYY format for display
        });
    }
    return days;
}

/**
 * Navigate to previous day
 * @param {Date} currentDate - Current date object
 * @returns {Date} New date object set to previous day
 */
export function getPreviousDay(currentDate) {
    const newDate = new Date(currentDate);
    newDate.setDate(newDate.getDate() - 1);
    return newDate;
}

/**
 * Navigate to next day
 * @param {Date} currentDate - Current date object
 * @returns {Date} New date object set to next day
 */
export function getNextDay(currentDate) {
    const newDate = new Date(currentDate);
    newDate.setDate(newDate.getDate() + 1);
    return newDate;
}

/**
 * Initialize date inputs with current date (today in client's local timezone)
 * @returns {string} Today's date in YYYY-MM-DD format
 */
export function getTodayFormatted() {
    return formatDateForAPI(new Date());
}

/**
 * Get the first day of the current month.
 * @returns {string} First day of the current month in YYYY-MM-DD format.
 */
export function getFirstDayOfCurrentMonth() {
    const today = new Date();
    const firstDay = new Date(today.getFullYear(), today.getMonth(), 1);
    return formatDateForAPI(firstDay);
}

/**
 * Get the last day of the current month.
 * @returns {string} Last day of the current month in YYYY-MM-DD format.
 */
export function getLastDayOfCurrentMonth() {
    const today = new Date();
    const firstDayOfNextMonth = new Date(today.getFullYear(), today.getMonth() + 1, 1);
    const lastDay = new Date(firstDayOfNextMonth - 1); // Subtract 1 millisecond (or 1 day)
    return formatDateForAPI(lastDay);
}

/**
 * Get the first day (Monday) of the week for a given date.
 * @param {Date} [date=new Date()] - The date to get the week for. Defaults to today.
 * @returns {string} First day of the week (Monday) in YYYY-MM-DD format.
 */
export function getFirstDayOfWeek(date = new Date()) {
    const d = new Date(date);
    const day = d.getDay(); // 0 is Sunday, 1 is Monday, ...
    const diff = d.getDate() - day + (day === 0 ? -6 : 1); // Adjust when day is Sunday
    const monday = new Date(d.setDate(diff));
    return formatDateForAPI(monday);
}

/**
 * Get the last day (Sunday) of the week for a given date.
 * @param {Date} [date=new Date()] - The date to get the week for. Defaults to today.
 * @returns {string} Last day of the week (Sunday) in YYYY-MM-DD format.
 */
export function getLastDayOfWeek(date = new Date()) {
    const monday = new Date(getFirstDayOfWeek(date)); // Get Monday of that week
    const sunday = new Date(monday);
    sunday.setDate(monday.getDate() + 6);
    return formatDateForAPI(sunday);
} 