<?php declare(strict_types=1);

class Seguro_Service_SalvarArquivoFormularioEcmPlugEssor
{
    const FILE_PATH_APOLICE = APPLICATION_PATH . '/upload_files/apolice_ecm';
    const FILE_PATH_PROPOSTA = APPLICATION_PATH . '/upload_files/proposta_ecm';
    const FILE_PATH_COTACAO = APPLICATION_PATH . '/upload_files/cotacao_ecm';

    const MAP_TIPO_ENVIO_FILE_PATH = [
        Seguro_Service_EnviarFormularioEcmPlugEssor::PDF_COTACAO => self::FILE_PATH_COTACAO,
        Seguro_Service_EnviarFormularioEcmPlugEssor::PDF_PROPOSTA => self::FILE_PATH_PROPOSTA,
        Seguro_Service_EnviarFormularioEcmPlugEssor::PDF_APOLICE =>  self::FILE_PATH_APOLICE,
    ];

    public function executar(string $nomeArquivo, int $tipoEnvio, string $pdfBase64): string
    {
        if (!isset(self::MAP_TIPO_ENVIO_FILE_PATH[$tipoEnvio])) {
            throw new InvalidArgumentException(sprintf('Tipo de envio inválido: %s', $tipoEnvio));
        }

        $dir = self::MAP_TIPO_ENVIO_FILE_PATH[$tipoEnvio];

        $caminhoArquivo = "{$dir}/{$nomeArquivo}";

        if (file_exists($caminhoArquivo)) {
            return $caminhoArquivo;
        }

        if (!is_dir($dir) && !mkdir($dir, 0755, true) && !is_dir($dir)) {
            throw new Exception(sprintf('Não foi possível criar o diretório %s', $dir));
        }

        $pdfContent = base64_decode($pdfBase64);

        if ($pdfContent === false) {
            throw new Exception('String base64 inválida.');
        }

        if (file_put_contents($caminhoArquivo, $pdfContent) === false) {
            throw new Exception('Erro ao salvar PDF.');
        }

        return $caminhoArquivo;
    }

    public static function getCaminhoArquivoPorTipoEnvio(int $tipoEnvio)
    {
        return self::MAP_TIPO_ENVIO_FILE_PATH[$tipoEnvio];
    }
}
