<?php

use MintyPHP\Router;
use MintyPHP\Support\Guard;
use MintyPHP\Service\Access\PermissionService;
use MintyPHP\Service\Audit\AuditServicesFactory;

Guard::requireLogin();
Guard::requirePermissionOrForbidden(PermissionService::USER_LIFECYCLE_AUDIT_VIEW);

if (strtoupper((string) ($_SERVER['REQUEST_METHOD'] ?? 'GET')) !== 'GET') {
    http_response_code(405);
    Router::json(['error' => 'method_not_allowed']);
}

$factory = new AuditServicesFactory();
$result = $factory->createUserLifecycleAuditService()->listPaged([
    'limit' => (int) ($_GET['limit'] ?? 20),
    'offset' => (int) ($_GET['offset'] ?? 0),
    'search' => trim((string) ($_GET['search'] ?? '')),
    'action' => trim((string) ($_GET['action'] ?? '')),
    'status' => trim((string) ($_GET['status'] ?? '')),
    'trigger_type' => trim((string) ($_GET['trigger_type'] ?? '')),
    'created_from' => trim((string) ($_GET['created_from'] ?? '')),
    'created_to' => trim((string) ($_GET['created_to'] ?? '')),
    'order' => (string) ($_GET['order'] ?? 'created_at'),
    'dir' => (string) ($_GET['dir'] ?? 'desc'),
]);

$rows = [];
foreach ((array) ($result['rows'] ?? []) as $row) {
    $status = strtolower(trim((string) ($row['status'] ?? '')));
    $statusBadge = 'neutral';
    if ($status === 'success') {
        $statusBadge = 'success';
    } elseif ($status === 'failed') {
        $statusBadge = 'danger';
    } elseif ($status === 'skipped') {
        $statusBadge = 'warning';
    }

    $rows[] = [
        'id' => (int) ($row['id'] ?? 0),
        'created_at' => dt((string) ($row['created_at'] ?? '')),
        'status' => $status,
        'status_badge' => $statusBadge,
        'action' => (string) ($row['action'] ?? ''),
        'trigger_type' => (string) ($row['trigger_type'] ?? ''),
        'reason_code' => (string) ($row['reason_code'] ?? ''),
        'target_user_uuid' => (string) ($row['target_user_uuid'] ?? ''),
        'target_user_email' => (string) ($row['target_user_email'] ?? ''),
        'restored_at' => dt((string) ($row['restored_at'] ?? '')),
    ];
}

Router::json([
    'data' => $rows,
    'total' => (int) ($result['total'] ?? 0),
]);
