<?php

declare(strict_types=1);

namespace App\Framework\Queue\Initializers;

use App\Framework\Cache\Cache;
use App\Framework\Database\ConnectionInterface;
use App\Framework\Database\EntityManager;
use App\Framework\DI\Container;
use App\Framework\DI\Initializer;
use App\Framework\Queue\Contracts\DeadLetterQueueInterface;
use App\Framework\Queue\ProductionJobPersistenceLayer;
use App\Framework\Queue\Queue;
use App\Framework\Queue\Services\DatabaseDeadLetterQueue;
use App\Framework\Queue\Services\DeadLetterManager;
use App\Framework\StateManagement\StateManager;

/**
 * Initializes Dead Letter Queue services
 */
final readonly class DeadLetterQueueInitializer
{
    #[Initializer]
    public function __invoke(Container $container): DeadLetterQueueInterface
    {
        // Register ProductionJobPersistenceLayer if not already registered
        if (!$container->has(ProductionJobPersistenceLayer::class)) {
            $persistenceLayer = new ProductionJobPersistenceLayer(
                stateManager: $container->get(StateManager::class),
                entityManager: $container->get(EntityManager::class),
                cache: $container->get(Cache::class)
            );
            $container->instance(ProductionJobPersistenceLayer::class, $persistenceLayer);
        }

        // Create Dead Letter Queue implementation
        $deadLetterQueue = new DatabaseDeadLetterQueue(
            connection: $container->get(ConnectionInterface::class),
            entityManager: $container->get(EntityManager::class),
            originalQueue: $container->get(Queue::class)
        );

        // Register Dead Letter Manager
        $deadLetterManager = new DeadLetterManager(
            deadLetterQueue: $deadLetterQueue,
            persistenceLayer: $container->get(ProductionJobPersistenceLayer::class)
        );
        $container->instance(DeadLetterManager::class, $deadLetterManager);

        return $deadLetterQueue;
    }
}
