<?php

use MintyPHP\Domain\Taxonomy\SystemAuditChannel;
use MintyPHP\Domain\Taxonomy\SystemAuditOutcome;
use MintyPHP\Service\Access\OperationsAuthorizationPolicy;
use MintyPHP\Service\Audit\SystemAuditService;
use MintyPHP\Support\Guard;

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

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

$result = app(SystemAuditService::class)->listPaged($filters);

$rows = [];
foreach ((array) ($result['rows'] ?? []) as $row) {
    $outcome = SystemAuditOutcome::normalizeOr((string) ($row['outcome'] ?? ''), SystemAuditOutcome::Success);
    $channel = SystemAuditChannel::normalizeOr((string) ($row['channel'] ?? ''), SystemAuditChannel::Web);

    $actorLabel = trim((string) ($row['actor_user_display_name'] ?? ''));
    if ($actorLabel === '') {
        $actorLabel = trim((string) ($row['actor_user_email'] ?? ''));
    }

    $rows[] = [
        'id' => (int) ($row['id'] ?? 0),
        'created_at' => dt((string) ($row['created_at'] ?? '')),
        'event_type' => (string) ($row['event_type'] ?? ''),
        'outcome' => $outcome->value,
        'outcome_badge' => $outcome->badgeVariant(),
        'outcome_label' => t($outcome->labelToken()),
        'channel' => strtoupper($channel->labelToken()),
        'actor_user_id' => (int) ($row['actor_user_id'] ?? 0),
        'actor_user_uuid' => (string) ($row['actor_user_uuid'] ?? ''),
        'actor_user_label' => $actorLabel !== '' ? $actorLabel : '-',
        'target_type' => (string) ($row['target_type'] ?? ''),
        'target_uuid' => (string) ($row['target_uuid'] ?? ''),
        'request_id' => (string) ($row['request_id'] ?? ''),
        'error_code' => (string) ($row['error_code'] ?? ''),
    ];
}

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