/**
 * PR-B.5 smoke — worker lock-lease TTL re-claim.
 *
 * The existing engine has a 5-minute lock TTL that re-releases stuck
 * `isChecking=true` rows at the start of each tick. The smoke spies
 * on prisma.monitor.updateMany to verify that:
 *   1. updateMany is called with a `lockedAt < lockCutoff` filter
 *   2. The TTL constant respects WORKER_LOCK_TTL_MS
 *
 * Run: npx tsx scripts/smoke/prb-5-worker-lock-ttl.ts
 */
import './_lib';
import { ok, fail } from './_lib';

// Force the TTL to 1 second so the assertion is unambiguous.
process.env.WORKER_LOCK_TTL_MS = '1000';

const captured: { where?: unknown }[] = [];
const prismaMod = require('../../src/lib/prisma') as { prisma: Record<string, unknown> };
prismaMod.prisma.monitor = {
    updateMany: (async (args: { where: unknown }) => {
        captured.push({ where: args.where });
        return { count: 3 }; // pretend 3 stuck locks were released
    }) as never,
    findMany: (async () => []) as never,
};
prismaMod.prisma.$transaction = (async () => []) as never;

async function main(): Promise<void> {
    const { runPendingChecks } = await import('../../src/lib/monitor-engine');
    await runPendingChecks(20);

    if (captured.length === 0) fail('PR-B.5 cleanup', 'expected updateMany to be called for TTL cleanup');
    const cleanupCall = captured[0];
    const where = cleanupCall.where as { isChecking?: boolean; lockedAt?: { lt: Date } };
    if (where.isChecking !== true) fail('PR-B.5 cleanup', 'expected isChecking=true filter');
    if (!where.lockedAt || !(where.lockedAt.lt instanceof Date)) fail('PR-B.5 cleanup', 'expected lockedAt.lt Date filter');
    ok('TTL sweep filters where isChecking=TRUE AND lockedAt < cutoff');

    const cutoffMs = (where.lockedAt!.lt as Date).getTime();
    const ageMs = Date.now() - cutoffMs;
    // Cutoff should be ~1000ms in the past (allow generous slack for CI clock jitter).
    if (ageMs < 500 || ageMs > 5000) fail('PR-B.5 ttl', `cutoff age ${ageMs}ms not ~1000ms (WORKER_LOCK_TTL_MS)`);
    ok('TTL cutoff honours WORKER_LOCK_TTL_MS env override');

    ok('PR-B.5 worker-lock-ttl smoke', 'crash-recovery re-claim path active');
}

main().catch((e) => fail('PR-B.5 crashed', String(e)));
