<?php

namespace NoahVet\Reef\RabbitMQ\Message\Handler;

use PhpAmqpLib\Message\AMQPMessage;

class ExecReefAMQPMessageHandler extends AbstractReefAMQPMessageHandler
{
    #[\Override]
    public function handleMessage(AMQPMessage $message): void
    {
        $commandLine = \implode(' ', $this->buildCommandLine());

        $process = \proc_open(
            $commandLine,
            [
                0 => ['pipe', 'r'],
                1 => ['pipe', 'w'],
                2 => ['pipe', 'w'],
            ],
            $pipes,
        );

        if (!$process) {
            throw new \LogicException("Can't proc_open : ".$commandLine);
        }

        \fwrite($pipes[0], $message->getBody());
        \fclose($pipes[0]);

        $output = (string) \stream_get_contents($pipes[1]).(string) \stream_get_contents($pipes[2]);

        \fclose($pipes[1]);
        \fclose($pipes[2]);

        $resultCode = \proc_close($process);

        if (0 !== $resultCode) {
            throw new \Exception(
                $commandLine." :\n".$output,
                $resultCode,
            );
        }
    }
}
