/**
 * P1-10 — scheduled email report decision function.
 *
 * Pure: given a ReportPreference shape and `now`, returns whether the
 * worker should send a report on this tick. Mirrors the same shape as
 * P2-5's rollup scheduler so callers operate the same way.
 *
 * Frequency intervals are real wall-clock durations, not calendar
 * months — "monthly" means 30 days. Operators wanting strict calendar
 * months can layer that in later; the day-count model keeps the
 * decision pure and dependency-free.
 */

const ONE_DAY_MS = 24 * 60 * 60 * 1000;

const FREQUENCY_DAYS: Record<string, number> = {
    weekly: 7,
    monthly: 30,
    quarterly: 90,
};

export function intervalMsFor(frequency: string): number | null {
    const days = FREQUENCY_DAYS[frequency];
    if (typeof days !== 'number') return null;
    return days * ONE_DAY_MS;
}

interface PreferenceShape {
    enabled: boolean;
    frequency: string;
    lastSentAt: Date | null;
}

export function shouldSendReportNow(
    pref: PreferenceShape,
    now: Date
): boolean {
    if (!pref.enabled) return false;

    const interval = intervalMsFor(pref.frequency);
    if (interval === null) return false; // unknown frequency — skip

    if (pref.lastSentAt === null) return true;

    // Future timestamp = "already ran" (clock-skew defence: an NTP
    // jump shouldn't fire duplicate sends).
    if (pref.lastSentAt.getTime() > now.getTime()) return false;

    return now.getTime() - pref.lastSentAt.getTime() >= interval;
}
