import { prisma } from '@/lib/prisma';

/**
 * True start of the CURRENT (most-recent) outage for a monitor, reconstructed
 * from raw heartbeats with no row cap.
 *
 * Three LIMIT-1 lookups (all served by Heartbeat's (monitorId, createdAt) and
 * (monitorId, status) indexes):
 *   1. most recent 'down'  → the tail of the outage (before any recovery 'up's)
 *   2. most recent 'up'/'maintenance' BEFORE that down → the outage's left edge
 *   3. first 'down' after that edge → the outage start
 *
 * This deliberately replaces the windowed `firstDownOfStreak` lookup in
 * monitor-engine, which was capped at (requiredDowns + requiredUps) rows and
 * so saturated long outages to a constant ~9m 30s. Matches the per-transition
 * reconstruction the downtime report already does, so emails and the audit
 * page agree on when an outage started.
 *
 * Returns null when the monitor has no 'down' heartbeat at all.
 */
export async function reconstructDownStart(monitorId: number): Promise<Date | null> {
    const lastDown = await prisma.heartbeat.findFirst({
        where: { monitorId, status: 'down' },
        orderBy: { createdAt: 'desc' },
        select: { createdAt: true },
    });
    if (!lastDown) return null;

    const priorUp = await prisma.heartbeat.findFirst({
        where: { monitorId, status: { in: ['up', 'maintenance'] }, createdAt: { lt: lastDown.createdAt } },
        orderBy: { createdAt: 'desc' },
        select: { createdAt: true },
    });

    const firstDown = await prisma.heartbeat.findFirst({
        where: {
            monitorId,
            status: 'down',
            ...(priorUp ? { createdAt: { gt: priorUp.createdAt } } : {}),
        },
        orderBy: { createdAt: 'asc' },
        select: { createdAt: true },
    });

    return firstDown?.createdAt ?? lastDown.createdAt;
}
