<?php declare(strict_types=1);

class Seguro_Service_EnviarFormularioFilaEcmPlugEssor
{
    private string $env;
    private Log_Model_EnvioFormularioEcmPlugEssor $log;
    private Seguro_Service_SalvarArquivoFormularioEcmPlugEssor $serviceSalvarArquivo;
    private Agro_RabbitMQ_EnvioFormularioEcmPlugEssor_RpcClient $rabbitmqClient;
    private Seguro_Service_NotificarErroEcmPlugEssor $serviceNotificarErro;

    public function __construct()
    {
        $os = strtoupper(substr(PHP_OS, 0, 3));
		$this->env = ($os == 'WIN') ? 'docker' : getenv('APPLICATION_ENV');
        $this->log = new Log_Model_EnvioFormularioEcmPlugEssor();
        $this->serviceSalvarArquivo = new Seguro_Service_SalvarArquivoFormularioEcmPlugEssor();
        $this->rabbitmqClient = new Agro_RabbitMQ_EnvioFormularioEcmPlugEssor_RpcClient(
            $this->env,
            'envio_formulario_ecm_plug_essor'
        );
        $this->serviceNotificarErro = new Seguro_Service_NotificarErroEcmPlugEssor();
    }

    /**
    * @param Seguro_Dto_FormularioFilaEcmPlugEssor[] $dtos
    */
    public function executar(array $dtos): array
    {
        $retorno = [];

        try {
            foreach ($dtos as $dto) {
                $mensagem = $dto->toArray();

                // Batch de mensagens
                try {
                    $this->rabbitmqClient->execute($mensagem);

                    $retorno['encaminhadoFila'][] = [
                        'id_proposta' => $dto->getIdProposta(),
                        'tipo_envio' => $dto->getTipoEnvio()
                    ];
                } catch (Throwable $e) {
                    $this->registrarErro($dto, $e);

                    $retorno['erros'][] = [
						'id_proposta' => $dto->getIdProposta(),
						'tipo_envio' => $dto->getTipoEnvio(),
						'mensagem' => $e->getMessage()
					];
                }
            }
        } finally {
            $this->rabbitmqClient->disconnect();
        }

        return $retorno;
    }

    private function registrarErro(Seguro_Dto_FormularioFilaEcmPlugEssor $dto, Throwable $e)
    {
        $modelProposta = new Seguro_Model_Propostas();

        $proposta = $modelProposta->find($dto->getIdProposta())->current();
        $caminhoArquivo = $this->serviceSalvarArquivo->executar(
            $modelProposta->getNomeArquivoEnvioEcm($proposta, $dto->getTipoEnvio()),
            $dto->getTipoEnvio(),
            $dto->getPdfBase64()
        );
        $idEndossoErp = (new Log_Model_PropostasTransmissao())->getIdEndossoErp($proposta->id);

        $erro = [
            'origem_erro' => 'AGRONET - envio fila',
            'tipo_erro' => get_class($e),
            'mensagem' => $e->getMessage(),
            'arquivo' => $e->getFile(),
            'linha' => $e->getLine(),
            'trace' => $e->getTraceAsString()
        ];
        
        $this->log->save([
            'id_proposta' => $dto->getIdProposta(),
            'id_endosso_erp' => $idEndossoErp,
            'fl_sucesso_envio' => false,
            'ds_chave_tipo_envio' => Seguro_Service_EnviarFormularioEcmPlugEssor::DESCRICAO_TIPOS_PDF[$dto->getTipoEnvio()],
            'ds_caminho_arquivo_agronet' => $caminhoArquivo,
            'json_erro' => json_encode($erro)
        ]);

        $this->serviceNotificarErro->executar($dto->getIdProposta(), $dto->getTipoEnvio(), $caminhoArquivo, $erro);
    }
}
