<?php
declare(strict_types=1);

require_once __DIR__ . '/_bootstrap.php';

$master = golder_master_pdo();
$jobId = golder_job_start($master, 'cron_cleanup');

try {
    $timedOutTabs = golder_expire_stale_web_session_tabs($master, golder_web_session_timeout_seconds());
    $timedOutSessions = golder_expire_inactive_web_sessions($master, golder_web_session_timeout_seconds());
    $gcDays = golder_web_session_gc_days();
    $deletedSessionTabs = golder_cleanup_web_session_tabs($master, $gcDays);
    $deletedSessions = golder_cleanup_web_sessions($master, $gcDays);
    $deletedRateRows = golder_rate_limit_cleanup($master, 72);
    $deletedNonces = golder_auth_cleanup_nonces($master, 24);

    $st = $master->prepare('UPDATE api_tokens SET revoked_at = UTC_TIMESTAMP() WHERE revoked_at IS NULL AND expires_at < UTC_TIMESTAMP()');
    $st->execute();
    $revokedExpired = (int)$st->rowCount();

    golder_job_finish($master, $jobId, 'ok', [
        'timed_out_tabs' => $timedOutTabs,
        'timed_out_sessions' => $timedOutSessions,
        'deleted_session_tabs' => $deletedSessionTabs,
        'deleted_sessions' => $deletedSessions,
        'deleted_rate_rows' => $deletedRateRows,
        'deleted_nonces' => $deletedNonces,
        'revoked_expired_tokens' => $revokedExpired,
    ]);

    echo "cron_cleanup finished.\n";
} catch (Throwable $e) {
    golder_job_finish($master, $jobId, 'error', ['error' => $e->getMessage()]);
    echo "cron_cleanup failed: {$e->getMessage()}\n";
    exit(1);
}


