<?php

declare(strict_types=1);

require_once __DIR__ . '/Env.php';

class Db
{
    private static ?PDO $pdo = null;

    public static function getConnection(): PDO
    {
        if (self::$pdo !== null) {
            return self::$pdo;
        }

        $dsn = Env::get('DB_DSN');
        if ($dsn === null) {
            throw new RuntimeException('DB_DSN is not configured');
        }

        $user = Env::get('DB_USER');
        $pass = Env::get('DB_PASS');
        $options = [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        ];

        self::$pdo = new PDO($dsn, $user ?: null, $pass ?: null, $options);

        if (str_starts_with($dsn, 'sqlite:')) {
            self::$pdo->exec('PRAGMA foreign_keys = ON');
        }

        return self::$pdo;
    }
}
