import logging
from app.core.module_framework.event_bus import event_bus
from app.core.postgres.base_pkg.base_client import BasePostgresClient
from uuid import UUID

logger = logging.getLogger(__name__)

def setup_takeoff_subscribers(postgres_client: BasePostgresClient):
    
    async def on_stock_not_enough(payload: dict):
        """
        Rollback Takeoff state to PENDING_REVIEW if Inventory doesn't have enough stock.
        [D6] Revert Logic Implementation.
        """
        takeoff_id_str = payload.get("takeoff_id")
        material_code = payload.get("material_code")
        
        if not takeoff_id_str:
            return
            
        logger.warning(f"[Takeoff Module] Nhận StockNotEnoughEvent cho vật tư {material_code}. Đang revert Takeoff {takeoff_id_str} về PENDING_REVIEW...")
        
        # In a real scenario, this would use a Command like `RevertTakeoffApprovalCommand`
        # and a Repository to update the database.
        # For demonstration of D6 execution:
        with postgres_client.get_connection() as conn:
            with conn.cursor() as cur:
                # Assuming schema `takeoff.takeoffs` exists
                try:
                    cur.execute("""
                        UPDATE takeoff.takeoffs
                        SET status = 'PENDING_REVIEW'
                        WHERE id = %s
                    """, (takeoff_id_str,))
                    conn.commit()
                    logger.info(f"[Takeoff Module] Đã Revert Takeoff {takeoff_id_str} thành công.")
                except Exception as e:
                    conn.rollback()
                    logger.error(f"[Takeoff Module] Revert Takeoff lỗi: {e}")

    event_bus.subscribe("StockNotEnoughEvent", on_stock_not_enough)
    logger.info("[Takeoff Module] Đã đăng ký lắng nghe StockNotEnoughEvent")
