<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Event\Retry;

use PpPhp\Core\Platform\Event\Queue\DeferredEvent;
use PpPhp\Core\Platform\Event\Queue\DeferredQueueManager;
use PpPhp\Core\Platform\Event\Retry\DeadLetter\DeadLetterQueue;

final class RetryRuntime
{
    private RetryPolicyRegistry $policies;
    private DeadLetterQueue $deadLetters;

    public function __construct(private readonly DeferredQueueManager $queue = new DeferredQueueManager())
    {
        $this->policies = new RetryPolicyRegistry();
        $this->deadLetters = new DeadLetterQueue();
    }

    public function execute(DeferredEvent $event, callable $handler, string $policy = 'immediate', int $maxAttempts = 3): RetryResult
    {
        $executor = new RetryExecutor($this->queue, $this->deadLetters, $this->policies->get($policy) ?? $this->policies->default());
        return $executor->execute($event, $handler, $maxAttempts);
    }

    public function policies(): RetryPolicyRegistry { return $this->policies; }
    public function deadLetters(): DeadLetterQueue { return $this->deadLetters; }

    public function summary(): array
    {
        return [
            'policies' => $this->policies->names(),
            'deadLetters' => $this->deadLetters->count(),
            'queue' => $this->queue->summary(),
        ];
    }
}
