from contextlib import contextmanager

from config.db_config import DatabaseConnectionError, get_db_connection


@contextmanager
def db_cursor(dictionary=False):
    """Open a database connection and cursor, then close both safely."""
    connection = None
    cursor = None

    try:
        connection = get_db_connection()
        if connection is None:
            raise DatabaseConnectionError("Database connection failed: connection is None.")

        cursor = connection.cursor(dictionary=dictionary)
        yield connection, cursor
        connection.commit()
    except DatabaseConnectionError as exc:
        raise DatabaseConnectionError(f"Database connection failed: {exc}") from exc
    except Exception:
        if connection and connection.is_connected():
            connection.rollback()
        raise
    finally:
        if cursor is not None:
            cursor.close()
        if connection and connection.is_connected():
            connection.close()