<?php

declare(strict_types=1);

namespace App\Domain\Jobs;

/**
 * What `JobRunner::run()` returns. Carries everything the HTTP envelope or
 * CLI output needs:
 *
 *   {"job":"recompute-scores","status":"success","items_processed":42,
 *    "duration_ms":81,"run_id":17}
 *
 * `errorMessage` is non-null only on `failure`. `runId` is the
 * `job_runs.id` of the final row.
 */
final class JobOutcome
{
    public function __construct(
        public readonly string $jobName,
        public readonly JobStatus $status,
        public readonly int $itemsProcessed,
        public readonly int $durationMs,
        public readonly int $runId,
        public readonly ?string $errorMessage = null,
    ) {
    }

    public function httpStatus(): int
    {
        return match ($this->status) {
            JobStatus::Success => 200,
            JobStatus::Failure => 500,
            JobStatus::SkippedLocked => 409,
            JobStatus::Running => 202,
        };
    }

    /**
     * @return array<string, mixed>
     */
    public function toArray(): array
    {
        $out = [
            'job' => $this->jobName,
            'status' => $this->status->value,
            'items_processed' => $this->itemsProcessed,
            'duration_ms' => $this->durationMs,
            'run_id' => $this->runId,
        ];
        if ($this->errorMessage !== null) {
            $out['error'] = $this->errorMessage;
        }

        return $out;
    }
}
