import logging
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from ..core.db import Database

logger = logging.getLogger(__name__)


class Transaction:
    def __init__(self, db: "Database"):
        self.db = db
        self.conn = None

    def __enter__(self):
        self.conn = self.db.pool.get_connection()
        self.db._local.connection = self.conn
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        try:
            if exc_type:
                logger.error(
                    "Transaction failed, rolling back.",
                    exc_info=(exc_type, exc_value, traceback),
                )
                self.conn.rollback()
                return False
            try:
                self.conn.commit()
                logger.info("Transaction committed successfully.")
            except Exception as e:
                logger.error("Error during commit, rolling back.", exc_info=True)
                self.conn.rollback()
                raise e
        finally:
            if hasattr(self.db._local, "connection"):
                del self.db._local.connection
            if self.conn:
                self.db.pool.release_connection(self.conn)
                self.conn = None
