<?php

use MintyPHP\Router;
use MintyPHP\Service\Access\PermissionService;
use MintyPHP\Service\Import\ImportServicesFactory;
use MintyPHP\Support\Guard;

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

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

$factory = new ImportServicesFactory();
$importAuditService = $factory->createImportAuditService();

$result = $importAuditService->listPaged([
    'limit' => (int) ($_GET['limit'] ?? 20),
    'offset' => (int) ($_GET['offset'] ?? 0),
    'search' => trim((string) ($_GET['search'] ?? '')),
    'profile_key' => trim((string) ($_GET['profile_key'] ?? '')),
    'status' => trim((string) ($_GET['status'] ?? '')),
    'created_from' => trim((string) ($_GET['created_from'] ?? '')),
    'created_to' => trim((string) ($_GET['created_to'] ?? '')),
    'user_id' => (int) ($_GET['user_id'] ?? 0),
    'order' => (string) ($_GET['order'] ?? 'started_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 === 'partial') {
        $statusBadge = 'warning';
    } elseif ($status === 'failed') {
        $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),
        'started_at' => dt((string) ($row['started_at'] ?? '')),
        'profile_key' => (string) ($row['profile_key'] ?? ''),
        'status' => $status,
        'status_badge' => $statusBadge,
        '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,
    ];
}

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