import psycopg
from psycopg.rows import dict_row

class DatabaseConnection:
    _connection = None

    @classmethod
    def connect(
        cls,
        dbname: str,
        user: str,
        password: str | None = None,
        host: str = "localhost",
        port: int = 5432,
        **kwargs,
    ):
        """
        Connect to PostgreSQL.
        Example:
            DatabaseConnection.connect(dbname="mydb", user="postgres", password="secret")
        """
        if cls._connection is None:
            dsn = psycopg.conninfo.make_conninfo(
                dbname=dbname,
                user=user,
                password=password,
                host=host,
                port=port,
                **kwargs
            )
            cls._connection = psycopg.connect(
                dsn,
                row_factory=dict_row,          
                autocommit=False           
            )
        return cls._connection

    @classmethod
    def get_connection(cls):
        if cls._connection is None:
            raise ValueError("Database not connected. Call connect() first.")
        return cls._connection

    @classmethod
    def close(cls):
        if cls._connection:
            cls._connection.close()
            cls._connection = None