<?php

use MintyPHP\Service\Access\OperationsAuthorizationPolicy;
use MintyPHP\Support\Guard;

Guard::requireLogin();
Guard::requireAbilityOrForbidden(OperationsAuthorizationPolicy::ABILITY_ADMIN_API_AUDIT_VIEW);
gridRequireGetRequest();

$filters = gridParseFiltersFromSchemaFile(__DIR__ . '/filter-schema.php');

$result = app(\MintyPHP\Service\Audit\ApiAuditService::class)->listPaged($filters);

$rows = [];
foreach ($result['rows'] as $row) {
    $statusCode = (int) ($row['status_code'] ?? 0);
    $statusBadge = gridResolveBadgeVariant(
        $statusCode >= 500 ? '5xx' : ($statusCode >= 400 ? '4xx' : ($statusCode >= 200 ? '2xx' : 'other')),
        ['2xx' => 'success', '4xx' => 'warning', '5xx' => 'danger']
    );

    $userLabel = trim((string) ($row['user_display_name'] ?? ''));
    $userEmail = trim((string) ($row['user_email'] ?? ''));
    if ($userLabel === '') {
        $userLabel = $userEmail !== '' ? $userEmail : '-';
    }

    $rows[] = [
        'id' => (int) ($row['id'] ?? 0),
        'request_id' => (string) ($row['request_id'] ?? ''),
        'created_at' => dt((string) ($row['created_at'] ?? '')),
        'method' => strtoupper((string) ($row['method'] ?? '')),
        'path' => (string) ($row['path'] ?? ''),
        'status_code' => $statusCode,
        'status_badge' => $statusBadge,
        'duration_ms' => (int) ($row['duration_ms'] ?? 0),
        'error_code' => (string) ($row['error_code'] ?? ''),
        'tenant_id' => (int) ($row['tenant_id'] ?? 0),
        'tenant_label' => (string) ($row['tenant_description'] ?? ''),
        'tenant_uuid' => (string) ($row['tenant_uuid'] ?? ''),
        'user_id' => (int) ($row['user_id'] ?? 0),
        'user_label' => $userLabel,
        'user_uuid' => (string) ($row['user_uuid'] ?? ''),
        'ip' => (string) ($row['ip'] ?? ''),
    ];
}

gridJsonDataResult($rows, (int) ($result['total'] ?? 0));
