<?php

use MintyPHP\Domain\Taxonomy\ScheduledJobRunStatus;
use MintyPHP\Domain\Taxonomy\ScheduledJobTriggerType;
use MintyPHP\Service\Access\OperationsAuthorizationPolicy;
use MintyPHP\Support\Guard;

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

$jobId = (int) ($id ?? 0);
if ($jobId <= 0) {
    gridJsonDataResult([], 0);
}

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

$result = app(\MintyPHP\Service\Scheduler\ScheduledJobService::class)->listRunsByJobId($jobId, [
    'limit' => $filters['limit'] ?? 10,
    'offset' => $filters['offset'] ?? 0,
    'search' => $filters['search'] ?? '',
    'status' => $filters['status'] ?? '',
    'trigger_type' => $filters['trigger_type'] ?? '',
    'order' => $filters['order'] ?? 'started_at',
    'dir' => $filters['dir'] ?? 'desc',
]);

$rows = [];
foreach ((array) ($result['rows'] ?? []) as $row) {
    $status = ScheduledJobRunStatus::normalizeOr((string) ($row['status'] ?? ''), ScheduledJobRunStatus::Failed);
    $triggerType = ScheduledJobTriggerType::normalizeOr((string) ($row['trigger_type'] ?? ''), ScheduledJobTriggerType::Scheduler);

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

    $rows[] = [
        'id' => (int) ($row['id'] ?? 0),
        'run_uuid' => (string) ($row['run_uuid'] ?? ''),
        'trigger_type' => $triggerType->value,
        'trigger_type_label' => t($triggerType->labelToken()),
        'status' => $status->value,
        'status_badge' => $status->badgeVariant(),
        'status_label' => t($status->labelToken()),
        'started_at' => dt((string) ($row['started_at'] ?? '')),
        'finished_at' => dt((string) ($row['finished_at'] ?? '')),
        'duration_ms' => (int) ($row['duration_ms'] ?? 0),
        'error_code' => (string) ($row['error_code'] ?? ''),
        'actor_label' => $actorLabel,
    ];
}

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