<?php

namespace KeyLair;

use PDO;
use PDOException;

/**
 * Thin PDO wrapper. Always uses prepared statements via the caller;
 * this class only owns the connection.
 */
class Database
{
    private static ?PDO $instance = null;

    public static function connection(): PDO
    {
        if (self::$instance === null) {
            $config = Config::get('db');

            $dsn = sprintf(
                'mysql:host=%s;port=%d;dbname=%s;charset=%s',
                $config['host'],
                $config['port'],
                $config['database'],
                $config['charset']
            );

            try {
                self::$instance = new PDO($dsn, $config['username'], $config['password'], [
                    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                    PDO::ATTR_EMULATE_PREPARES   => false,
                ]);
            } catch (PDOException $e) {
                // Never leak DSN/credentials to the browser.
                error_log('Database connection failed: ' . $e->getMessage());
                http_response_code(500);
                die('Service temporarily unavailable. Please try again later.');
            }
        }

        return self::$instance;
    }

    /** Force a fresh connection on the next call. Used by test harnesses after process forking. */
    public static function reset(): void
    {
        self::$instance = null;
    }
}
