<?php

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

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

$scheduledJobService = app(\MintyPHP\Service\Scheduler\ScheduledJobService::class);

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

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

$rows = [];
foreach ((array) ($result['rows'] ?? []) as $row) {
    $status = ScheduledJobStatus::tryNormalize((string) ($row['last_run_status'] ?? ''));

    $jobKey = (string) ($row['job_key'] ?? '');
    $jobLabel = trim((string) ($row['label'] ?? ''));
    if ($jobLabel === '' && $jobKey !== '') {
        $jobLabel = ucfirst(str_replace('_', ' ', strtolower($jobKey)));
    }

    $rows[] = [
        'id' => (int) ($row['id'] ?? 0),
        'job_key' => $jobKey,
        'label' => $jobLabel,
        'enabled' => (int) ($row['enabled'] ?? 0),
        'schedule_summary' => $scheduledJobService->scheduleSummary($row),
        'next_run_at' => dt((string) ($row['next_run_at'] ?? '')),
        'last_run_finished_at' => dt((string) ($row['last_run_finished_at'] ?? '')),
        'last_run_status' => $status?->value ?? '',
        'last_run_status_badge' => $status?->badgeVariant() ?? 'neutral',
        'last_run_status_label' => $status !== null ? t($status->labelToken()) : '-',
        'last_error' => trim((string) ($row['last_error_code'] ?? '')) !== ''
            ? trim((string) ($row['last_error_code'] ?? ''))
            : trim((string) ($row['last_error_message'] ?? '')),
    ];
}

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