package com.erp.inventory.event;

import com.erp.inventory.service.StockWarningCheckService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * 库存变更事件监听器
 * 监听库存变更事件并触发预警检查
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class StockChangedEventListener {

    private final StockWarningCheckService warningCheckService;

    /**
     * 监听库存变更事件并执行预警检查
     * 使用@Async实现异步执行，不阻塞主流程
     */
    @Async
    @EventListener
    public void onStockChanged(StockChangedEvent event) {
        log.debug("收到库存变更事件: skuCode={}, warehouseId={}, changeType={}, changeQty={}",
                event.getSkuCode(), event.getWarehouseId(), event.getChangeType(), event.getChangeQuantity());

        try {
            warningCheckService.checkAndTriggerWarnings(
                    event.getSkuCode(),
                    event.getSkuName(),
                    event.getWarehouseId()
            );
        } catch (Exception e) {
            log.error("处理库存变更事件失败: skuCode={}, error={}",
                    event.getSkuCode(), e.getMessage(), e);
        }
    }
}
