package com.ycwl.basic.face.pipeline.stages;

import com.ycwl.basic.biz.FaceStatusManager;
import com.ycwl.basic.enums.FaceCutStatus;
import com.ycwl.basic.face.pipeline.core.FaceMatchingContext;
import com.ycwl.basic.pipeline.annotation.StageConfig;
import com.ycwl.basic.pipeline.core.AbstractPipelineStage;
import com.ycwl.basic.pipeline.core.StageResult;
import com.ycwl.basic.pipeline.enums.StageOptionalMode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 设置任务状态Stage
 * 负责为新用户设置任务状态为待处理
 *
 * 职责:
 * 1. 仅在isNew=true时执行
 * 2. 调用taskStatusBiz.setFaceCutStatus(faceId, 0)
 */
@Slf4j
@Component
@StageConfig(
    stageId = "set_task_status",
    optionalMode = StageOptionalMode.FORCE_ON,
    description = "设置新用户任务状态"
)
public class SetTaskStatusStage extends AbstractPipelineStage<FaceMatchingContext> {

    @Autowired
    private FaceStatusManager faceStatusManager;

    @Override
    public String getName() {
        return "SetTaskStatus";
    }

    @Override
    protected boolean shouldExecuteByBusinessLogic(FaceMatchingContext context) {
        // 只有新用户才执行
        if (!context.isNew()) {
            log.debug("非新用户，跳过设置任务状态，faceId={}", context.getFaceId());
            return false;
        }
        return true;
    }

    @Override
    protected StageResult<FaceMatchingContext> doExecute(FaceMatchingContext context) {
        Long faceId = context.getFaceId();

        // 防御性检查：只有新用户才执行
        if (!context.isNew()) {
            log.debug("非新用户，跳过设置任务状态，faceId={}", faceId);
            return StageResult.skipped("非新用户");
        }

        try {
            faceStatusManager.setFaceCutStatus(faceId, FaceCutStatus.CUTTING);
            log.debug("设置新用户任务状态: faceId={}, status=0", faceId);
            return StageResult.success("任务状态已设置");

        } catch (Exception e) {
            log.error("设置任务状态失败，faceId={}", faceId, e);
            // 任务状态设置失败不影响主流程，返回降级
            return StageResult.degraded("任务状态设置失败: " + e.getMessage());
        }
    }
}
