<?php
declare(strict_types=1);

namespace Momentry;

use PDO;
use PDOException;
use RuntimeException;

defined('ABSPATH') || exit;

class Database {
    private static ?PDO $instance = null;
    
    public static function get_instance(): PDO {
        if (self::$instance === null) {
            self::$instance = self::create_connection();
        }
        return self::$instance;
    }
    
    private static function create_connection(): PDO {
        $host = getenv('MOMENTRY_DB_HOST') ?: 'localhost';
        $port = getenv('MOMENTRY_DB_PORT') ?: '5432';
        $dbname = getenv('MOMENTRY_DB_NAME') ?: 'momentry';
        $user = getenv('MOMENTRY_DB_USER') ?: 'accusys';
        $password = getenv('MOMENTRY_DB_PASSWORD') ?: '';
        
        $dsn = "pgsql:host={$host};port={$port};dbname={$dbname}";
        
        try {
            $pdo = new PDO($dsn, $user, $password, [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES => false,
            ]);
            
            return $pdo;
        } catch (PDOException $e) {
            throw new RuntimeException(
                'Database connection failed: ' . $e->getMessage()
            );
        }
    }
    
    public static function get_schema(): string {
        return getenv('MOMENTRY_DB_SCHEMA') ?: 'dev';
    }
}