<?php

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

Guard::requireLogin();
Guard::requirePermissionOrForbidden(PermissionService::API_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->createApiAuditService()->listPaged([
    'limit' => (int) ($_GET['limit'] ?? 20),
    'offset' => (int) ($_GET['offset'] ?? 0),
    'search' => trim((string) ($_GET['search'] ?? '')),
    'status' => trim((string) ($_GET['status'] ?? '')),
    'method' => trim((string) ($_GET['method'] ?? '')),
    'created_from' => trim((string) ($_GET['created_from'] ?? '')),
    'created_to' => trim((string) ($_GET['created_to'] ?? '')),
    'tenant_id' => (int) ($_GET['tenant_id'] ?? 0),
    'user_id' => (int) ($_GET['user_id'] ?? 0),
    'order' => (string) ($_GET['order'] ?? 'created_at'),
    'dir' => (string) ($_GET['dir'] ?? 'desc'),
]);

$rows = [];
foreach ($result['rows'] as $row) {
    $statusCode = (int) ($row['status_code'] ?? 0);
    $statusBadge = 'neutral';
    if ($statusCode >= 200 && $statusCode < 300) {
        $statusBadge = 'success';
    } elseif ($statusCode >= 400 && $statusCode < 500) {
        $statusBadge = 'warning';
    } elseif ($statusCode >= 500) {
        $statusBadge = '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'] ?? ''),
    ];
}

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