<?php
declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';

/* =========================
   HELPERS
   ========================= */

function lock_user(PDO $pdo, int $userId, string $reason): void
{
    // Never auto-lock platform or super admins
    $stmt = $pdo->prepare("
        SELECT role_key, status
        FROM users
        WHERE id = ?
        LIMIT 1
    ");
    $stmt->execute([$userId]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$user) {
        return;
    }

    if (in_array($user['role_key'], ['super_admin', 'platform_admin'], true)) {
        return;
    }

    // Only lock active accounts
    if ($user['status'] !== 'active') {
        return;
    }

    $pdo->beginTransaction();

    try {
        $pdo->prepare("
            UPDATE users
            SET status = 'locked'
            WHERE id = ?
              AND status = 'active'
        ")->execute([$userId]);

        auditLog(
            $userId,
            null,
            'system',
            'admin_auto_lock',
            ['reason' => $reason]
        );

        $pdo->commit();

    } catch (Throwable $e) {
        $pdo->rollBack();
        // Silent fail — auto-lock must never crash system jobs
    }
}

/* =========================
   RULE 1 — DESTRUCTIVE SPIKE
   ========================= */

$q = $pdo->query("
    SELECT actor_user_id, COUNT(*) cnt
    FROM audit_logs
    WHERE action IN (
        'user_delete',
        'company_delete',
        'module_toggle',
        'subscription_cancel'
    )
      AND created_at >= NOW() - INTERVAL 10 MINUTE
      AND actor_user_id IS NOT NULL
    GROUP BY actor_user_id
    HAVING cnt >= 3
");

foreach ($q as $row) {
    lock_user(
        $pdo,
        (int)$row['actor_user_id'],
        'destructive_action_spike'
    );
}

/* =========================
   RULE 2 — ACTIVITY FROM NEW IP
   ========================= */

$q = $pdo->query("
    SELECT DISTINCT a.actor_user_id
    FROM audit_logs a
    LEFT JOIN audit_logs b
      ON a.actor_user_id = b.actor_user_id
     AND a.ip_address = b.ip_address
     AND b.created_at < a.created_at
    WHERE b.id IS NULL
      AND a.actor_user_id IS NOT NULL
      AND a.created_at >= NOW() - INTERVAL 10 MINUTE
");

foreach ($q as $row) {
    lock_user(
        $pdo,
        (int)$row['actor_user_id'],
        'activity_from_new_ip'
    );
}
