<?php

use MintyPHP\Router;
use MintyPHP\Service\Access\PermissionService;
use MintyPHP\Service\Scheduler\SchedulerServicesFactory;
use MintyPHP\Support\Guard;

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

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

$jobId = (int) ($id ?? 0);
if ($jobId <= 0) {
    Router::json(['data' => [], 'total' => 0]);
}

$factory = new SchedulerServicesFactory();
$result = $factory->createScheduledJobService()->listRunsByJobId($jobId, [
    'limit' => (int) ($_GET['limit'] ?? 10),
    'offset' => (int) ($_GET['offset'] ?? 0),
    'search' => trim((string) ($_GET['search'] ?? '')),
    'status' => trim((string) ($_GET['status'] ?? '')),
    'trigger_type' => trim((string) ($_GET['trigger_type'] ?? '')),
    '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 === 'failed') {
        $statusBadge = 'danger';
    } elseif ($status === 'skipped') {
        $statusBadge = 'warning';
    }

    $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' => strtolower(trim((string) ($row['trigger_type'] ?? ''))),
        'status' => $status,
        'status_badge' => $statusBadge,
        '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,
    ];
}

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