<?php

declare(strict_types=1);

$renderExternalUrl = rtrim((string)(getenv('RENDER_EXTERNAL_URL') ?: ''), '/');
$storedCertificate = null;
$certificateStorageDir = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'storage' . DIRECTORY_SEPARATOR . 'certificados';
$certificateStoragePath = $certificateStorageDir . DIRECTORY_SEPARATOR . 'certificado.json';
if (is_file($certificateStoragePath)) {
    $storedCertificate = json_decode((string)file_get_contents($certificateStoragePath), true);
}
$defaultHomologationUrl = $renderExternalUrl !== ''
    ? 'mock://ciot/api/v1'
    : 'http://127.0.0.1:8081/api/v1';

return [
    // Padrao em homologacao. Para producao, altere CIOT_ENV para production.
    'environment' => getenv('CIOT_ENV') ?: 'homologation',

    // Credencial do provedor/integradora CIOT, somente se o provedor exigir.
    'provider_token' => getenv('CIOT_PROVIDER_TOKEN') ?: '',

    // Homologacao local pronta para teste. Substitua pela URL oficial do provedor quando tiver as credenciais.
    'homologation_url' => getenv('CIOT_HOMOLOGATION_URL') ?: $defaultHomologationUrl,
    'production_url' => getenv('CIOT_PRODUCTION_URL') ?: 'https://api.exemplo-ciot.com.br/v1',

    'timeout' => (int)(getenv('CIOT_TIMEOUT') ?: 30),
    'connect_timeout' => (int)(getenv('CIOT_CONNECT_TIMEOUT') ?: 10),
    'log_file' => dirname(__DIR__) . DIRECTORY_SEPARATOR . 'logs' . DIRECTORY_SEPARATOR . 'ciot.log',
    'cors_allowed_origin' => getenv('CIOT_CORS_ALLOWED_ORIGIN') ?: '*',

    // Certificado A1 instalado para teste: GRG TRANSPORTES LTDA:32256965000136.
    // PHP/cURL usa arquivo para mTLS; mantenha vazio em homologacao local e configure o PFX quando o provedor exigir.
    'certificate_subject' => 'GRG TRANSPORTES LTDA:32256965000136',
    'certificate_cnpj' => '32256965000136',
    'certificate_thumbprint' => '5FFC96F49371C5E734D16121CDC2CA8C7740E15D',
    'client_certificate_path' => getenv('CIOT_CLIENT_CERT_PATH') ?: ($storedCertificate['path'] ?? null),
    'client_certificate_password' => getenv('CIOT_CLIENT_CERT_PASSWORD') ?: ($storedCertificate['password'] ?? null),
    'client_certificate_type' => getenv('CIOT_CLIENT_CERT_TYPE') ?: ($storedCertificate['type'] ?? 'P12'),
    'certificate_storage_dir' => $certificateStorageDir,
    'certificate_storage_path' => $certificateStoragePath,
];
