<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Event\Retry\DeadLetter;

use PpPhp\Core\Platform\Event\Queue\DeferredEvent;

final class FailedEvent
{
    public function __construct(
        private readonly string $id,
        private readonly DeferredEvent $event,
        private readonly string $reason,
        private readonly int $attempts,
        private readonly string $failedAt = ''
    ) {}

    public static function fromDeferredEvent(DeferredEvent $event, string $reason, int $attempts): self
    {
        return new self('failed_' . $event->id(), $event, $reason, $attempts);
    }

    public function id(): string { return $this->id; }
    public function event(): DeferredEvent { return $this->event; }
    public function reason(): string { return $this->reason; }
    public function attempts(): int { return $this->attempts; }
    public function failedAt(): string { return $this->failedAt !== '' ? $this->failedAt : date('c'); }

    public function toArray(): array
    {
        return [
            'id' => $this->id,
            'event' => $this->event->toArray(),
            'reason' => $this->reason,
            'attempts' => $this->attempts,
            'failedAt' => $this->failedAt(),
        ];
    }
}
