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.partners.application.commands import UpdatePartnerScoreCommand, UpdatePartnerScoreCommandHandler

logger = logging.getLogger(__name__)

def setup_partners_subscribers(postgres_client: BasePostgresClient):
    
    async def on_invoice_fraud_detected(payload: dict):
        """
        [D6] Lắng nghe cảnh báo Fraud từ Invoices để trừ điểm Partner.
        """
        tax_code = payload.get('supplier_tax_code')
        if not tax_code:
            return
            
        logger.warning(f"[Partners Module] Nhận Event Fraud cho NCC {tax_code}. Đang tiến hành xử phạt...")
        
        command = UpdatePartnerScoreCommand(
            tax_code=tax_code,
            deduct_points=20, # Trừ 20 điểm mỗi lần dính fraud
            reason="Hệ thống Invoices phát hiện gian lận (Fraud Detected)"
        )
        
        handler = UpdatePartnerScoreCommandHandler(postgres_client)
        try:
            handler.handle(command)
        except Exception as e:
            logger.error(f"[Partners Module] Lỗi khi xử phạt đối tác: {e}")

    event_bus.subscribe("InvoiceFraudDetectedEvent", on_invoice_fraud_detected)
    logger.info("[Partners Module] Đã đăng ký lắng nghe InvoiceFraudDetectedEvent")
