<?php

namespace App\Domain\Shared\Domain\Model;

abstract class Job
{
    public JobStatus $status;
    public \DateTimeImmutable $createdAt;
    public ?\DateTimeImmutable $startedAt = null;
    public ?\DateTimeImmutable $completedAt = null;
    public ?string $failureReason = null;
    public int $attempts = 0;
    public int $maxAttempts = 3;
    public array $context = [];

    public function __construct(
        public readonly string $id,
        public readonly string $type
    ) {
        $this->status = JobStatus::PENDING;
        $this->createdAt = new \DateTimeImmutable();
    }

    public function start(): void
    {
        $this->status = JobStatus::IN_PROGRESS;
        $this->startedAt = new \DateTimeImmutable();
        $this->attempts++;
    }

    public function complete(): void
    {
        $this->status = JobStatus::COMPLETED;
        $this->completedAt = new \DateTimeImmutable();
    }

    public function fail(string $reason): void
    {
        $this->failureReason = $reason;
        $this->status = $this->attempts >= $this->maxAttempts
            ? JobStatus::FAILED
            : JobStatus::PENDING;
        $this->completedAt = new \DateTimeImmutable();
    }

    public function cancel(): void
    {
        $this->status = JobStatus::CANCELLED;
        $this->completedAt = new \DateTimeImmutable();
    }

    public function canBeRetried(): bool
    {
        return $this->status === JobStatus::FAILED && $this->attempts < $this->maxAttempts;
    }
}
