<?php

use MintyPHP\Domain\Taxonomy\ImportAuditStatus;
use MintyPHP\Service\Access\OperationsAuthorizationPolicy;
use MintyPHP\Service\Audit\ImportAuditService;
use MintyPHP\Support\Guard;

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

$importAuditService = app(ImportAuditService::class);

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

$result = $importAuditService->listPaged($filters);

$rows = [];
foreach ((array) ($result['rows'] ?? []) as $row) {
    $status = ImportAuditStatus::normalizeOr((string) ($row['status'] ?? ''), ImportAuditStatus::Failed);

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

    $rows[] = [
        'id' => (int) ($row['id'] ?? 0),
        'started_at' => dt((string) ($row['started_at'] ?? '')),
        'profile_key' => (string) ($row['profile_key'] ?? ''),
        'status' => $status->value,
        'status_badge' => $status->badgeVariant(),
        'status_label' => t($status->labelToken()),
        'duration_ms' => (int) ($row['duration_ms'] ?? 0),
        'rows_total' => (int) ($row['rows_total'] ?? 0),
        'created_count' => (int) ($row['created_count'] ?? 0),
        'skipped_count' => (int) ($row['skipped_count'] ?? 0),
        'failed_count' => (int) ($row['failed_count'] ?? 0),
        'user_uuid' => (string) ($row['user_uuid'] ?? ''),
        'user_label' => $userLabel,
    ];
}

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