/**
 * P1-10 smoke — scheduled-report decision function.
 *
 * Validates the contract without hitting the DB or SMTP. The actual
 * end-to-end flow (worker tick -> DB read -> build -> email) requires
 * a live environment and is exercised by the worker integration test
 * (manual: enable a ReportPreference for an admin, wait for the next
 * tick, watch the email arrive).
 *
 * Run: npx tsx scripts/smoke/p1-10-report-scheduler.ts
 */
import './_lib';
import { ok, fail } from './_lib';
import { shouldSendReportNow, intervalMsFor } from '../../src/lib/services/report-scheduler';

function main(): void {
    if (intervalMsFor('weekly') !== 7 * 86400_000) fail('P1-10 weekly', 'wrong interval');
    if (intervalMsFor('monthly') !== 30 * 86400_000) fail('P1-10 monthly', 'wrong interval');
    if (intervalMsFor('quarterly') !== 90 * 86400_000) fail('P1-10 quarterly', 'wrong interval');
    if (intervalMsFor('hourly') !== null) fail('P1-10 unknown', 'should be null');
    ok('intervalMsFor maps known frequencies + null on unknown');

    const NOW = new Date('2026-06-01T12:00:00Z');

    if (!shouldSendReportNow({ enabled: true, frequency: 'weekly', lastSentAt: null }, NOW)) {
        fail('P1-10 never-sent', 'null lastSentAt should be sendable');
    }
    ok('first-time send (lastSentAt=null) returns true');

    if (shouldSendReportNow({ enabled: false, frequency: 'weekly', lastSentAt: null }, NOW)) {
        fail('P1-10 disabled', 'disabled should never send');
    }
    ok('disabled preference never sends');

    const eightAgo = new Date(NOW.getTime() - 8 * 86400_000);
    if (!shouldSendReportNow({ enabled: true, frequency: 'weekly', lastSentAt: eightAgo }, NOW)) {
        fail('P1-10 weekly-elapsed', 'should send after 8 days when frequency=weekly');
    }
    ok('weekly preference resends after 8 days');

    const sixAgo = new Date(NOW.getTime() - 6 * 86400_000);
    if (shouldSendReportNow({ enabled: true, frequency: 'weekly', lastSentAt: sixAgo }, NOW)) {
        fail('P1-10 weekly-not-elapsed', 'should not send after 6 days when frequency=weekly');
    }
    ok('weekly preference rejects re-send at 6 days');

    const future = new Date(NOW.getTime() + 86400_000);
    if (shouldSendReportNow({ enabled: true, frequency: 'weekly', lastSentAt: future }, NOW)) {
        fail('P1-10 future-clock-skew', 'future lastSentAt should not re-send');
    }
    ok('clock-skew defence (future lastSentAt) holds');

    ok('P1-10 report-scheduler smoke', 'scheduler decisions match contract');
}

main();
