package com.qqchen.deploy.backend.deploy.listener;

import com.qqchen.deploy.backend.deploy.enums.DeployRecordStatusEnums;
import com.qqchen.deploy.backend.deploy.service.IDeployRecordService;
import com.qqchen.deploy.backend.workflow.dto.event.ApprovalCompletedEvent;
import com.qqchen.deploy.backend.workflow.dto.event.ApprovalTaskCreatedEvent;
import com.qqchen.deploy.backend.workflow.enums.ApprovalResultEnum;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * 部署记录审批状态同步监听器
 * 监听审批相关事件，同步更新部署记录状态
 *
 * @author qqchen
 * @since 2025-11-02
 */
@Slf4j
@Component
public class DeployRecordApprovalStatusSyncListener {

    private static final String DEPLOYMENT_CATEGORY_CODE = "DEPLOYMENT";

    @Resource
    private IDeployRecordService deployRecordService;

    /**
     * 监听审批任务创建事件
     * 当审批任务创建时，更新部署记录状态为"待审批"
     */
    @EventListener
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void handleApprovalTaskCreated(ApprovalTaskCreatedEvent event) {
        // 判断是否为部署类型的工作流
        if (!isDeploymentWorkflow(event.getWorkflowCategoryCode())) {
            return;
        }

        try {
            log.debug("处理审批任务创建事件: workflowInstanceId={}, nodeId={}", 
                    event.getWorkflowInstanceId(), event.getNodeId());
            
            // 更新部署记录状态为"待审批"
            deployRecordService.updateStatusToPendingApproval(event.getWorkflowInstanceId());
            
            log.info("部署记录状态已更新为待审批: workflowInstanceId={}", event.getWorkflowInstanceId());
        } catch (Exception e) {
            log.error("同步部署记录状态失败（审批任务创建）: workflowInstanceId={}", 
                    event.getWorkflowInstanceId(), e);
            // 不影响主流程，只记录错误
        }
    }

    /**
     * 监听审批完成事件
     * 根据审批结果更新部署记录状态
     */
    @EventListener
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void handleApprovalCompleted(ApprovalCompletedEvent event) {
        // 判断是否为部署类型的工作流
        if (!isDeploymentWorkflow(event.getWorkflowCategoryCode())) {
            return;
        }

        try {
            log.debug("处理审批完成事件: workflowInstanceId={}, nodeId={}, result={}", 
                    event.getWorkflowInstanceId(), event.getNodeId(), event.getResult());
            
            // 根据审批结果更新部署记录状态
            if (event.getResult() == ApprovalResultEnum.APPROVED) {
                // 审批通过，更新为运行中
                deployRecordService.updateStatusFromApproval(event.getWorkflowInstanceId(), true);
            } else if (event.getResult() == ApprovalResultEnum.REJECTED) {
                // 审批被拒绝，更新为已取消
                deployRecordService.updateStatusFromApproval(event.getWorkflowInstanceId(), false);
            }
            
            log.info("部署记录状态已同步（审批完成）: workflowInstanceId={}, result={}", 
                    event.getWorkflowInstanceId(), event.getResult());
        } catch (Exception e) {
            log.error("同步部署记录状态失败（审批完成）: workflowInstanceId={}", 
                    event.getWorkflowInstanceId(), e);
            // 不影响主流程，只记录错误
        }
    }

    /**
     * 判断是否为部署类型的工作流
     */
    private boolean isDeploymentWorkflow(String workflowCategoryCode) {
        return DEPLOYMENT_CATEGORY_CODE.equals(workflowCategoryCode);
    }
}

