from uuid import UUID
import logging
from app.core.module_framework.event_bus import event_bus
from app.core.postgres.base_pkg.base_client import BasePostgresClient
from app.modules.invoices.application.commands import MarkInvoicePaidCommand, MarkInvoicePaidCommandHandler

logger = logging.getLogger(__name__)

def setup_invoices_subscribers(postgres_client: BasePostgresClient):
    
    async def on_invoice_reconciled(payload: dict):
        """
        Event Handler: Xử lý khi nhận được InvoiceReconciledIntegrationEvent từ module Banking.
        """
        invoice_id_str = payload.get('invoice_id')
        if not invoice_id_str:
            return
            
        logger.info(f"[Invoices Module] Nhận được Event Đối soát Hóa đơn: {invoice_id_str}. Đang cập nhật trạng thái...")
        
        command = MarkInvoicePaidCommand(
            invoice_id=UUID(invoice_id_str)
        )
        
        handler = MarkInvoicePaidCommandHandler(postgres_client)
        
        try:
            handler.handle(command)
        except Exception as e:
            logger.error(f"[Invoices Module] Lỗi khi cập nhật trạng thái hóa đơn từ Event: {e}")

    # Đăng ký với Event Bus
    event_bus.subscribe("InvoiceReconciledIntegrationEvent", on_invoice_reconciled)
    logger.info("[Invoices Module] Đã đăng ký lắng nghe InvoiceReconciledIntegrationEvent")
