<?php

namespace NoahVet\Reef\RabbitMQ\Message\Handler;

use PhpAmqpLib\Message\AMQPMessage;
use Psr\Log\LoggerInterface;
use Symfony\Component\Process\InputStream;
use Symfony\Component\Process\Process;

class ProcessReefAMQPMessageHandler extends AbstractReefAMQPMessageHandler
{
    public function __construct(
        protected readonly LoggerInterface $logger,
    ) {
    }

    #[\Override]
    public function handleMessage(AMQPMessage $message): void
    {
        $input = new InputStream();
        $input->write($message->getBody());

        // Prepare process execution
        $process = new Process($this->buildCommandLine(), timeout: null);
        $process->setInput($input);

        // Start process
        $process->start();

        $input->close();

        $process->wait();

        $this->logger->debug(
            'Executed AMQP process', [
                'errorOutput' => $process->getErrorOutput(),
                'exitCode' => $process->getExitCode(),
                'output' => $process->getOutput(),
            ],
        );

        // Error bubbling
        if (0 !== $process->getExitCode()) {
            throw new \Exception(
                $process->getOutput().' '.$process->getErrorOutput(),
                $process->getExitCode() ?? -1,
            );
        }
    }
}
