<?php

use MintyPHP\Domain\Taxonomy\MailLogStatus;
use MintyPHP\Service\Access\OperationsAuthorizationPolicy;
use MintyPHP\Support\Guard;

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

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

$mailLogService = app(\MintyPHP\Service\Mail\MailLogService::class);
$result = $mailLogService->listPaged([
    'limit' => $filters['limit'],
    'offset' => $filters['offset'],
    'search' => $filters['search'],
    'order' => $filters['order'],
    'dir' => $filters['dir'],
    'status' => $filters['status'],
    'created_from' => $filters['created_from'],
    'created_to' => $filters['created_to'],
]);

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

    $rows[] = [
        'id' => $row['id'] ?? null,
        'to_email' => $row['to_email'] ?? '',
        'subject' => $row['subject'] ?? '',
        'template' => $row['template'] ?? '',
        'status' => $status->value,
        'status_badge' => $status->badgeVariant(),
        'status_label' => t($status->labelToken()),
        'created_at' => dt($row['created_at'] ?? ''),
        'sent_at' => dt($row['sent_at'] ?? ''),
    ];
}

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