<?php
// cleanup_cron.php
// Nota: ping_logs são limpos automaticamente pela política de retenção do TimescaleDB (30 dias).
// Este script apenas arquiva registros antigos de alerts_sent.
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/license.php';

if (!_mp_env_ready()) { exit(0); }
$_s = license_check(); if ($_s['status'] === 'blocked') { exit(0); } unset($_s);

$pdo = db();

$diasRetencao = 30;

echo "Iniciando limpeza de registros de alertas...\n";

try {
    $stmtAlerts = $pdo->prepare("
        DELETE FROM alerts_sent
        WHERE sent_at < (NOW() - ? * INTERVAL '1 day')
    ");
    $stmtAlerts->execute([$diasRetencao]);
    $deletedAlerts = $stmtAlerts->rowCount();

    echo "[SUCESSO] {$deletedAlerts} alertas antigos removidos.\n";
    echo "[INFO] ping_logs gerenciados automaticamente pelo TimescaleDB (retenção 30 dias).\n";

} catch (Exception $e) {
    echo "[ERRO] Falha ao expurgar alertas: " . $e->getMessage() . "\n";
}

// #39 Retry de webhooks falhos (até 3 tentativas: 5min, 30min, 2h)
try {
    $tableExists = $pdo->query("SELECT to_regclass('webhook_retries')")->fetchColumn();
    if ($tableExists) {
        $retries = $pdo->query("SELECT * FROM webhook_retries WHERE attempts < 3 AND next_retry_at <= NOW() LIMIT 50")->fetchAll();
        $retried = 0; $retriedOk = 0;
        foreach ($retries as $retry) {
            $retried++;
            $context = stream_context_create(['http' => [
                'method' => 'POST',
                'header' => "Content-Type: application/json\r\n",
                'content' => $retry['payload'],
                'timeout' => 8
            ]]);
            $result = @file_get_contents($retry['target'], false, $context);
            $httpCode = 0;
            foreach ($http_response_header ?? [] as $h) {
                if (preg_match('#HTTP/\S+\s+(\d+)#', $h, $m)) { $httpCode = (int)$m[1]; break; }
            }
            $success = $result !== false && $httpCode >= 200 && $httpCode < 400;
            if ($success) {
                $pdo->prepare("DELETE FROM webhook_retries WHERE id = ?")->execute([$retry['id']]);
                $retriedOk++;
            } else {
                $nextAttempt = (int)$retry['attempts'] + 1;
                if ($nextAttempt >= 3) {
                    $pdo->prepare("DELETE FROM webhook_retries WHERE id = ?")->execute([$retry['id']]);
                } else {
                    $delays = [5, 30, 120];
                    $delay  = $delays[$nextAttempt] ?? 120;
                    $pdo->prepare("UPDATE webhook_retries SET attempts = ?, next_retry_at = NOW() + ? * INTERVAL '1 minute' WHERE id = ?")
                        ->execute([$nextAttempt, $delay, $retry['id']]);
                }
            }
        }
        if ($retried > 0) echo "[RETRY] {$retried} webhooks reprocessados, {$retriedOk} OK.\n";
    }
} catch (Exception $e) {
    echo "[ERRO] Retry webhooks: " . $e->getMessage() . "\n";
}

// Limpa sessões de usuário mais antigas que 90 dias
try {
    $pdo->exec("DELETE FROM user_sessions WHERE created_at < (NOW() - INTERVAL '90 days')");
} catch (Exception $e) { /* tabela pode não existir ainda */ }
