<?php

declare(strict_types=1);

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(
        private readonly LoggerInterface $logger,
    ) {
    }

    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,
            );
        }
    }
}
