<?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']);
}

$factory = new SchedulerServicesFactory();
$scheduledJobService = $factory->createScheduledJobService();

$result = $scheduledJobService->listPaged([
    'limit' => (int) ($_GET['limit'] ?? 20),
    'offset' => (int) ($_GET['offset'] ?? 0),
    'search' => trim((string) ($_GET['search'] ?? '')),
    'enabled' => trim((string) ($_GET['enabled'] ?? '')),
    'status' => trim((string) ($_GET['status'] ?? '')),
    'order' => (string) ($_GET['order'] ?? 'job_key'),
    'dir' => (string) ($_GET['dir'] ?? 'asc'),
]);

$rows = [];
foreach ((array) ($result['rows'] ?? []) as $row) {
    $status = strtolower(trim((string) ($row['last_run_status'] ?? '')));
    $statusBadge = 'neutral';
    if ($status === 'success') {
        $statusBadge = 'success';
    } elseif ($status === 'failed') {
        $statusBadge = 'danger';
    } elseif ($status === 'running') {
        $statusBadge = 'info';
    } elseif ($status === 'skipped') {
        $statusBadge = 'warning';
    }

    $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,
        'last_run_status_badge' => $statusBadge,
        'last_error' => trim((string) ($row['last_error_code'] ?? '')) !== ''
            ? trim((string) ($row['last_error_code'] ?? ''))
            : trim((string) ($row['last_error_message'] ?? '')),
    ];
}

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