<?php declare(strict_types=1);

class Agro_Essor_Plug_EcmDocumentosEndossos
{
    public function execute(Agro_Essor_Plug_Dto_EcmDocumentosEndossosRequest $dto): ?array
    {
        $url = PLUG_URL . "/v1/formularios/{$dto->idDocumento}/endossos/{$dto->idEndosso}";
        
        $ch = curl_init($url);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $header = ['Content-Type: application/json'];

        $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);

        $data = json_decode($response, true);
        
        if (empty($data) || $httpCode != 200) {
            $prefixo = (APPLICATION_ENV != 'production') ? "[PLUG] " : "";
            
            if (!empty($data) && array_key_exists('message', $data)) {
                throw new Exception($prefixo . $data['mensagem'], 1);
            }
            
            throw new Exception("{$prefixo} Erro ao buscar documento.", 1);
        }
        
        return $data;
    }
}
