<?php declare(strict_types=1);

class Agro_Essor_Plug_FormulariosConsulta
{
    public function execute(Agro_Essor_Plug_Dto_FormulariosConsultaRequest $dto): array
    {
        $url = PLUG_URL . "/v1/formularios/{$dto->idEndosso}/documentos?relatorio_id={$dto->idRelatorio}";
        $ch = curl_init($url);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $header = ['Content-Type: application/json'];
        if (APPLICATION_ENV == 'production') {
            $bearerToken = Agro_Essor_Plug_Auth::login();
            $header[] = "Authorization: Bearer {$bearerToken}";
        }

        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        $response = json_decode($response, true);

        $prefixo = (APPLICATION_ENV != 'production') ? "[PLUG] " : "";

        if (empty($response['base64']) || $httpCode != 200) {
             if (array_key_exists('msgs', $response)) {
                throw new Exception($prefixo . $response['msgs']);
            }
            
            if (array_key_exists('mensagem', $response)) {
                throw new Exception($prefixo . $response['mensagem']);
            }

            throw new Exception("{$prefixo} Erro ao buscar arquivo.");
        }
        
        return $response;
    }
}