// File: src/scheduling/calendars.js
// Calendar-aware date utilities (Mon–Fri working days, no holiday support yet)

/**
 * Add N working days to a date.
 * @param {Date|string} startDate
 * @param {number} days  positive = forward, negative = backward
 * @returns {Date}
 */
export function addWorkingDays(startDate, days) {
    const d   = new Date(startDate);
    const abs = Math.abs(days);
    const dir = days >= 0 ? 1 : -1;
    let added = 0;
    while (added < abs) {
        d.setDate(d.getDate() + dir);
        const dow = d.getDay(); // 0=Sun, 6=Sat
        if (dow !== 0 && dow !== 6) added++;
    }
    return d;
}

/**
 * Count working days from startDate (exclusive) to endDate (inclusive).
 * @param {Date|string} startDate
 * @param {Date|string} endDate
 * @returns {number}
 */
export function workingDaysBetween(startDate, endDate) {
    const start = new Date(startDate);
    const end   = new Date(endDate);
    let count = 0;
    const cur = new Date(start);
    cur.setDate(cur.getDate() + 1);
    while (cur <= end) {
        const dow = cur.getDay();
        if (dow !== 0 && dow !== 6) count++;
        cur.setDate(cur.getDate() + 1);
    }
    return count;
}

/**
 * Convert a working-day offset from baseDate to a calendar date.
 * @param {Date|string} baseDate  day 0
 * @param {number} dayNum         working days from base
 * @returns {Date}
 */
export function dayNumToDate(baseDate, dayNum) {
    if (dayNum === 0) return new Date(baseDate);
    return addWorkingDays(baseDate, dayNum);
}

/**
 * Duration in working days.
 * @param {number} value
 * @param {'hour'|'day'|'week'} unit
 * @returns {number}
 */
export function toDays(value, unit) {
    switch (unit) {
        case 'hour': return value / 8;
        case 'week': return value * 5;
        default:     return value;
    }
}
