<?php

require_once __DIR__ . '/../RpcClientBase.php';

use PhpAmqpLib\Message\AMQPMessage;

class Agro_RabbitMQ_EnvioFormularioEcmPlugEssor_RpcClient extends Agro_RabbitMQ_RpcClientBase
{
    public function __construct(string $env, string $nomeFila)
    {
        parent::__construct($env);
        $this->nomeFila = $nomeFila;
        $this->channel->confirm_select();
        $this->channel->queue_declare(
            $this->nomeFila,
            false,
            true,
            false,
            false
        );
    }

    public function execute(array $params)
    {
        $payload = json_encode($params, JSON_THROW_ON_ERROR);
        $this->run($payload);
    }

    public function run($payload)
    {
        if (!$this->connection || !$this->connection->isConnected()) {
            throw new Exception('Conexão RabbitMQ indisponível.');
        }

        if (!$this->channel || !$this->channel->is_open()) {
            throw new Exception('Canal RabbitMQ indisponível.');
        }

        $msg = new AMQPMessage(
            $payload,
            ['delivery_mode' => 2]
        );

        $this->channel->basic_publish(
            $msg,
            '',
            $this->nomeFila
        );

        $this->channel->wait_for_pending_acks(5);
    }

    public function disconnect(): void
    {
        if ($this->channel && $this->channel->is_open()) {
            $this->channel->close();
        }
       
        if ($this->connection && $this->connection->isConnected()) {
            $this->connection->close();
        }
    }
}