<?php

namespace App\Jobs;

use App\ScheduledTasks\ScheduledTaskRunner;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Mtc\MercuryDataModels\ScheduledTaskRun;
use Throwable;

class RunScheduledTaskJob implements ShouldQueue, ShouldBeUnique
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    /**
     * Job-level hard limit: the worker kills the job past this point.
     * Derived from the task's summed action timeouts plus headroom, so the
     * hard limit always exceeds the per-action budgets.
     */
    public int $timeout;

    public int $uniqueFor;

    public function __construct(public readonly ScheduledTaskRun $run)
    {
        $this->onQueue('sync');

        $actionTimeouts = $run->task?->actions
            ->sum(fn ($action) => $action->timeout_seconds
                ?? config('scheduled_tasks.defaults.action_timeout')) ?? 0;

        $this->timeout = max(60, $actionTimeouts) + config('scheduled_tasks.defaults.job_headroom');
        $this->uniqueFor = $this->timeout + 60;
    }

    public function uniqueId(): string
    {
        return 'scheduled-task-run-' . $this->run->id;
    }

    public function handle(ScheduledTaskRunner $runner): void
    {
        $runner->execute($this->run);
    }

    public function failed(Throwable $exception): void
    {
        app(ScheduledTaskRunner::class)
            ->markFailed($this->run, 'Job failed: ' . $exception->getMessage());
    }
}
