import logging

from django.conf import settings
from django.db import transaction


logger = logging.getLogger(__name__)


def on_shipment_created(sender, **kwargs):
    """
    Shipment 创建后的处理。

    当前通过 Celery task 异步发送企业微信通知，避免阻塞主流程。
    """
    if not getattr(settings, "SHIPMENT_CREATED_WECOM_NOTIFY_ENABLED", True):
        return
    if getattr(settings, "TESTING", False):
        return

    shipment = kwargs.get("instance")
    created_by = kwargs.get("created_by")
    if shipment is None:
        logger.warning("[shipment.handlers] shipment_created 信号缺少 instance，跳过通知")
        return

    logger.info(
        "[shipment.handlers] 收到 shipment_created 信号: sender=%s, shipment_id=%s",
        sender,
        getattr(shipment, "id", None),
    )

    def _enqueue_task():
        try:
            from shipment.tasks import notify_shipment_created_wecom

            notify_shipment_created_wecom.delay(
                shipment_id=shipment.id,
                created_by_id=getattr(created_by, "id", None),
            )
        except Exception:
            logger.exception(
                "[shipment.handlers] 投递 notify_shipment_created_wecom task 失败（已忽略，不影响主流程）"
            )

    transaction.on_commit(_enqueue_task)
