<?php

declare(strict_types=1);

namespace App\Support;

use PDO;
use PDOException;

final class Database
{
    private static ?PDO $connection = null;
    private static array $config = [];

    public static function configure(array $config): void
    {
        self::$config = $config;
        self::$connection = null; // reset on reconfigure
    }

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

        $driver = self::$config['db_driver'] ?? 'sqlite';

        if ($driver === 'pgsql') {
            $host = self::$config['db_host'] ?? '127.0.0.1';
            $port = self::$config['db_port'] ?? '5432';
            $dbname = self::$config['db_database'] ?? '';
            $user = self::$config['db_username'] ?? '';
            $password = self::$config['db_password'] ?? '';

            $dsn = "pgsql:host={$host};port={$port};dbname={$dbname}";
            self::$connection = new PDO($dsn, $user, $password);
        } else {
            $path = self::$config['db_path'] ?? self::$config['db_path'] ?? '';
            $directory = dirname($path);
            if (!is_dir($directory)) {
                mkdir($directory, 0775, true);
            }
            self::$connection = new PDO('sqlite:' . $path);
            self::$connection->exec('PRAGMA foreign_keys = ON');
        }

        self::$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        self::$connection->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

        return self::$connection;
    }

    public static function isPostgres(): bool
    {
        return (self::$config['db_driver'] ?? 'sqlite') === 'pgsql';
    }

    public static function lastInsertId(): string
    {
        if (self::isPostgres()) {
            return self::$connection->query('SELECT lastval()')->fetchColumn();
        }
        return self::$connection->lastInsertId();
    }
}
