<?php
declare(strict_types=1);

$localConfig = __DIR__ . DIRECTORY_SEPARATOR . 'database.local.php';
if (is_file($localConfig)) {
    $local = require $localConfig;
    if (!is_array($local)) {
        throw new RuntimeException('config/database.local.php must return an array.');
    }

    return [
        'driver' => 'mysql',
        'host' => (string) ($local['host'] ?? '127.0.0.1'),
        'port' => max(1, (int) ($local['port'] ?? 3306)),
        'database' => (string) ($local['database'] ?? ''),
        'username' => (string) ($local['username'] ?? ''),
        'password' => (string) ($local['password'] ?? ''),
        'charset' => 'utf8mb4',
    ];
}

$env = static function (string $key, mixed $default = null): mixed {
    if (function_exists('app_env')) {
        return app_env($key, $default);
    }

    $value = getenv($key);
    if ($value === false || $value === null || $value === '') {
        return $default;
    }

    return $value;
};

$port = (int) $env('DB_PORT', 3306);
if ($port <= 0) {
    $port = 3306;
}

return [
    'driver' => 'mysql',
    'host' => (string) $env('DB_HOST', '127.0.0.1'),
    'port' => $port,
    'database' => (string) $env('DB_DATABASE', 'quaeriva'),
    'username' => (string) $env('DB_USERNAME', 'root'),
    'password' => (string) $env('DB_PASSWORD', ''),
    'charset' => 'utf8mb4',
];
