<?php

namespace NoahVet\Reef\Command\RabbitMQ;

use NoahVet\Reef\RabbitMQ\Consumer\Factory\ReefMQConsumerFactory;
use NoahVet\Reef\RabbitMQ\Consumer\ReefMQConsumerInterface;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

#[AsCommand(name: 'reef:rabbitmq:process')]
class RabbitMQProcessCommand extends Command
{
    private ?ReefMQConsumerInterface $consumer = null;

    public function __construct(
        private readonly ReefMQConsumerFactory $taskConsumerFactory,
    ) {
        parent::__construct('reef:rabbitmq:process');
    }

    #[\Override]
    public function execute(InputInterface $input, OutputInterface $output): int
    {
        if (
            \function_exists('pcntl_signal')
            && \defined('SIGTERM')
            && \defined('SIGQUIT')
            && \defined('SIGINT')
        ) {
            \pcntl_signal(\SIGTERM, fn (int $signal) => $this->stopSignalHandler($signal, $this->consumer));
            \pcntl_signal(\SIGQUIT, fn (int $signal) => $this->stopSignalHandler($signal, $this->consumer));
            \pcntl_signal(\SIGINT, fn (int $signal) => $this->stopSignalHandler($signal, $this->consumer));
        }

        $this->consumer = $this->taskConsumerFactory->createConsumer();

        try {
            while ($this->consumer->isOpen()) {
                $this->consumer->consume();
            }
        } catch (\Exception) {
            return self::FAILURE;
        }

        return self::SUCCESS;
    }

    #[\Override]
    protected function configure(): void
    {
        $this->setDescription('Wait for incoming messages from RabbitMQ');
    }

    private function stopSignalHandler(int $signal, ?ReefMQConsumerInterface $consumer): void
    {
        $consumer?->stopConsume();
        if (null === $consumer) {
            // Fermeture prématurée
            exit(0);
        }
    }
}
