<?php
declare(strict_types=1);

$root = dirname(__DIR__, 2);
$envFile = $root . '/.env';

if (is_file($envFile)) {
    foreach (file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [] as $line) {
        $line = trim($line);
        if ($line === '' || str_starts_with($line, '#') || !str_contains($line, '=')) continue;
        [$k, $v] = explode('=', $line, 2);
        $k = trim($k);
        $v = trim($v);
        if ((str_starts_with($v, '"') && str_ends_with($v, '"')) || (str_starts_with($v, "'") && str_ends_with($v, "'"))) {
            $v = substr($v, 1, -1);
        }
        $_ENV[$k] = $v;
        putenv($k . '=' . $v);
    }
}

$schema = $_ENV['CADASTRO_DB_SCHEMA']
    ?? $_ENV['MUNICIPIO_JEQUIE_BCI_DB_SCHEMA']
    ?? $_ENV['MUNICIPIO_JEQUIE_BI_IPTU_GEO_SCHEMA']
    ?? 'mun_jequie';

$schema = preg_replace('/[^a-zA-Z0-9_]/', '', (string)$schema) ?: 'mun_jequie';

return [
    'host' => $_ENV['DB_HOST'] ?? '127.0.0.1',
    'port' => $_ENV['DB_PORT'] ?? '5432',
    'name' => $_ENV['DB_DATABASE'] ?? ($_ENV['DB_NAME'] ?? 'postgres'),
    'user' => $_ENV['DB_USERNAME'] ?? ($_ENV['DB_USER'] ?? 'postgres'),
    'pass' => $_ENV['DB_PASSWORD'] ?? ($_ENV['DB_PASS'] ?? ''),
    'schema' => [$schema],
    'cadastro_schema' => $schema,
];
