<?php

use MintyPHP\Domain\Taxonomy\ScheduledJobRunStatus;
use MintyPHP\Domain\Taxonomy\SchedulerRuntimeResult;
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Router;
use MintyPHP\Session;
use MintyPHP\Support\Flash;
use MintyPHP\Support\Guard;

$session = app(SessionStoreInterface::class)->all();
Guard::requireLogin();
Guard::requireAbility(\MintyPHP\Service\Access\OperationsAuthorizationPolicy::ABILITY_ADMIN_JOBS_RUN_NOW);

$jobId = (int) ($id ?? 0);
if (strtoupper((string) (requestInput()->method())) !== 'POST') {
    Router::redirect("admin/scheduled-jobs/edit/$jobId");
}
$errorBag = formErrors();
if (!Session::checkCsrfToken()) {
    $errorBag->addGlobal(t('Form expired, please try again'));
    flashFormErrors($errorBag, "admin/scheduled-jobs/edit/$jobId", 'scheduled_job_run');
    Router::redirect("admin/scheduled-jobs/edit/$jobId");
}

$result = app(\MintyPHP\Service\Scheduler\SchedulerRunService::class)->runJobNow($jobId, (int) ($session['user']['id'] ?? 0));
if (!($result['ok'] ?? false)) {
    $error = (string) ($result['error'] ?? '');
    if ($error === SchedulerRuntimeResult::LockNotAcquired->value) {
        $errorBag->addGlobal(t('Scheduler is already running'));
    } elseif ($error === 'job_not_found') {
        $errorBag->addGlobal(t('Scheduled job not found'));
    } else {
        $errorBag->addGlobal(t('Scheduled job run failed'));
    }
    $targetScope = $error === 'job_not_found' ? 'admin/scheduled-jobs' : "admin/scheduled-jobs/edit/$jobId";
    flashFormErrors($errorBag, $targetScope, 'scheduled_job_run');
    Router::redirect($targetScope);
}

$status = strtolower(trim((string) ($result['status'] ?? '')));
if ($status === ScheduledJobRunStatus::Skipped->value) {
    Flash::success(t('Scheduled job run skipped'), "admin/scheduled-jobs/edit/$jobId", 'scheduled_job_run_skipped');
} else {
    Flash::success(t('Scheduled job run completed'), "admin/scheduled-jobs/edit/$jobId", 'scheduled_job_run_success');
}
Router::redirect("admin/scheduled-jobs/edit/$jobId");
