package cn.iocoder.yudao.module.energy.listener;

import cn.iocoder.yudao.module.energy.enums.DeductionStatusEnum;
import cn.iocoder.yudao.module.energy.event.DetailAuditPassedEvent;
import cn.iocoder.yudao.module.energy.service.account.EnergyAccountService;
import cn.iocoder.yudao.module.energy.service.detail.HydrogenDetailService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

@Component
@Slf4j
public class AccountEventListener {

    @Resource
    private EnergyAccountService accountService;
    @Resource
    private HydrogenDetailService detailService;

    /**
     * 明细审核通过 → 执行扣款
     * BEFORE_COMMIT: 资金操作，必须同事务
     * 
     * 注意：此监听器处理审核后扣款场景（站点配置 auto_deduct=false）
     * 自动扣款场景（auto_deduct=true）在明细创建时已完成
     */
    @TransactionalEventListener(phase = TransactionPhase.BEFORE_COMMIT)
    public void onDetailAuditPassed(DetailAuditPassedEvent event) {
        // TODO: 需要从 asset 模块获取站点配置判断是否需要扣款
        // 当前简化实现：审核通过后统一扣款
        log.info("[onDetailAuditPassed] deduct: detailId={}, amount={}", 
                event.getDetailId(), event.getCustomerAmount());
        accountService.deduct(event.getCustomerId(), event.getContractId(),
                event.getCustomerAmount(), event.getDetailId(), null, "审核后扣款");
        detailService.updateDeductionStatus(event.getDetailId(), DeductionStatusEnum.DEDUCTED.getStatus());
    }
}
