/**
 * PR-B.1 smoke — heartbeat-monitor liveness sweeper.
 *
 * Exercises the pure decision function shouldMarkHeartbeatDown across
 * the four cases that matter operationally: (1) never-pinged monitor,
 * (2) fresh ping, (3) stale ping requiring a new down row, (4) stale
 * ping that's already been marked down (idempotency).
 *
 * Run: npx tsx scripts/smoke/prb-1-heartbeat-sweeper.ts
 */
import './_lib';
import { ok, fail } from './_lib';
import { shouldMarkHeartbeatDown } from '../../src/lib/services/heartbeat-sweeper';

const t = (iso: string) => new Date(iso);

function main(): void {
    const monitor = { intervalSeconds: 3600 }; // hourly
    const now = t('2026-05-22T12:00:00Z');

    if (shouldMarkHeartbeatDown({ ...monitor, lastPingAt: null }, null, now) !== false) {
        fail('PR-B.1 never-pinged', 'never-pinged monitor should not be flipped down');
    }
    ok('never-pinged monitor is skipped (operator-managed first-ping state)');

    if (shouldMarkHeartbeatDown(
        { ...monitor, lastPingAt: t('2026-05-22T11:30:00Z') },
        null,
        now,
    ) !== false) {
        fail('PR-B.1 fresh ping', 'fresh ping should not be flipped down');
    }
    ok('fresh ping (30m ago, threshold 90m) is skipped');

    if (shouldMarkHeartbeatDown(
        { ...monitor, lastPingAt: t('2026-05-22T10:00:00Z') },
        null,
        now,
    ) !== true) {
        fail('PR-B.1 stale ping', 'stale ping should be flipped down');
    }
    ok('stale ping (2h ago, threshold 90m) is flipped down');

    if (shouldMarkHeartbeatDown(
        { ...monitor, lastPingAt: t('2026-05-22T10:00:00Z') },
        { id: 99, status: 'down', createdAt: t('2026-05-22T11:30:00Z') },
        now,
    ) !== false) {
        fail('PR-B.1 idempotent', 'already-down monitor should not be flipped down again');
    }
    ok('idempotent: already-down monitor not flipped again in same cycle');

    ok('PR-B.1 heartbeat-sweeper smoke', 'sweeper decision logic is sound');
}

main();
