<?php

declare(strict_types=1);

namespace TekDek\Employees;

use PDO;
use PDOException;

/**
 * Database connection singleton.
 */
class Database
{
    private static ?PDO $instance = null;

    /**
     * Get the PDO connection instance.
     */
    public static function getConnection(): PDO
    {
        if (self::$instance === null) {
            self::$instance = self::createConnection();
        }
        return self::$instance;
    }

    /**
     * Set a custom PDO instance (for testing).
     */
    public static function setConnection(PDO $pdo): void
    {
        self::$instance = $pdo;
    }

    /**
     * Reset the connection (for testing).
     */
    public static function reset(): void
    {
        self::$instance = null;
    }

    private static function createConnection(): PDO
    {
        $host = getenv('DB_HOST') ?: '127.0.0.1';
        $port = getenv('DB_PORT') ?: '3306';
        $name = getenv('DB_NAME') ?: 'tekdek';
        $user = getenv('DB_USER') ?: 'root';
        $pass = getenv('DB_PASS') ?: '';

        $dsn = "mysql:host={$host};port={$port};dbname={$name};charset=utf8mb4";

        try {
            $pdo = new PDO($dsn, $user, $pass, [
                PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES   => false,
            ]);
            return $pdo;
        } catch (PDOException $e) {
            http_response_code(500);
            echo json_encode(['error' => 'Database connection failed']);
            exit(1);
        }
    }
}
