<?php
/**
 * Migração: cria tabela latency_incidents
 * Rastreia períodos de latência alta com início, fim e duração
 */
require_once __DIR__ . '/db.php';
$pdo = db();

$pdo->exec("
    CREATE TABLE IF NOT EXISTS latency_incidents (
        id                      BIGSERIAL PRIMARY KEY,
        monitored_ip_id         INTEGER NOT NULL REFERENCES monitored_ips(id) ON DELETE CASCADE,
        threshold_ms            INTEGER NOT NULL,
        started_at              TIMESTAMPTZ NOT NULL,
        recovered_at            TIMESTAMPTZ,
        duration_seconds        INTEGER,
        peak_latency_ms         INTEGER NOT NULL,
        checks_above_threshold  INTEGER NOT NULL DEFAULT 1,
        alert_sent              BOOLEAN NOT NULL DEFAULT FALSE
    );

    CREATE INDEX IF NOT EXISTS idx_latency_incidents_ip_at
        ON latency_incidents(monitored_ip_id, started_at DESC);

    CREATE INDEX IF NOT EXISTS idx_latency_incidents_open
        ON latency_incidents(monitored_ip_id) WHERE recovered_at IS NULL;
");

echo "Tabela latency_incidents criada com sucesso.\n";
