import logging
from uuid import UUID
from app.core.module_framework.event_bus import event_bus
from app.core.postgres.base_pkg.base_client import BasePostgresClient
from app.modules.banking.application.commands import UnmatchTransactionCommand, UnmatchTransactionCommandHandler

logger = logging.getLogger(__name__)

def setup_banking_subscribers(postgres_client: BasePostgresClient):
    
    async def on_invoice_cancelled(payload: dict):
        """
        [D6] Xử lý khi nhận được InvoiceCancelledIntegrationEvent từ module Invoices.
        Rollback giao dịch ngân hàng về UNMATCHED.
        """
        invoice_id_str = payload.get('invoice_id')
        if not invoice_id_str:
            return
            
        logger.warning(f"[Banking Module] Nhận Event Hủy Hóa Đơn {invoice_id_str}. Đang revert các giao dịch liên quan...")
        
        command = UnmatchTransactionCommand(
            invoice_id=UUID(invoice_id_str)
        )
        
        handler = UnmatchTransactionCommandHandler(postgres_client)
        
        try:
            handler.handle(command)
        except Exception as e:
            logger.error(f"[Banking Module] Lỗi khi revert đối soát: {e}")

    event_bus.subscribe("InvoiceCancelledIntegrationEvent", on_invoice_cancelled)
    logger.info("[Banking Module] Đã đăng ký lắng nghe InvoiceCancelledIntegrationEvent")
