/**
 * Last Working Day (LWD) helpers for resignation & termination offboarding.
 */

export const LWD_FNF_READY_REMINDER_ACTION = 'LWD_FNF_READY_REMINDER';

export function normalizeDateOnly(value: Date | string | null | undefined): Date | null {
    if (value == null || value === '') return null;
    const d = value instanceof Date ? new Date(value) : new Date(String(value));
    if (Number.isNaN(d.getTime())) return null;
    d.setHours(0, 0, 0, 0);
    return d;
}

export function isLwdReached(
    lwd: Date | string | null | undefined,
    today: Date = new Date()
): boolean {
    const lwdDate = normalizeDateOnly(lwd);
    if (!lwdDate) return true;
    const t = normalizeDateOnly(today)!;
    return t >= lwdDate;
}

export function formatLwdDisplay(lwd: Date | string | null | undefined): string {
    const d = normalizeDateOnly(lwd);
    if (!d) return 'N/A';
    return d.toLocaleDateString('en-IN', { dateStyle: 'medium' });
}

/** Milliseconds from now until start of LWD date (00:00 local). Returns 0 if LWD is today or past. */
export function msUntilLwdMorning(lwd: Date | string): number {
    const lwdDate = normalizeDateOnly(lwd);
    if (!lwdDate) return 0;
    const now = new Date();
    const target = new Date(lwdDate);
    target.setHours(8, 0, 0, 0); // 08:00 local — align with daily cron
    const diff = target.getTime() - now.getTime();
    return diff > 0 ? diff : 0;
}
