<?php
declare(strict_types=1);

namespace Config;

use PDO;
use PDOException;

final class Database
{
    private static ?PDO $connection = null;

    public static function connection(): PDO
    {
        if (self::$connection) return self::$connection;

        $host = Env::get('DB_HOST', 'localhost');
        $db = Env::get('DB_NAME');
        $charset = Env::get('DB_CHARSET', 'utf8mb4');
        $socket = Env::get('DB_SOCKET', '');
        $port = Env::get('DB_PORT', '3306');

        $dsn = $socket
            ? "mysql:unix_socket={$socket};dbname={$db};charset={$charset}"
            : "mysql:host={$host};port={$port};dbname={$db};charset={$charset}";

        try {
            self::$connection = new PDO($dsn, Env::get('DB_USER'), Env::get('DB_PASS'), [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES => false,
            ]);
            return self::$connection;
        } catch (PDOException $e) {
            $debug = Env::get('APP_DEBUG', 'false') === 'true';
            throw new PDOException($debug ? 'Database connection failed: ' . $e->getMessage() : 'Database connection failed. Check .env credentials.');
        }
    }
}
