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

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 com.ycwl.basic.mapper.SourceMapper;
import com.ycwl.basic.mapper.VideoMapper;
import com.ycwl.basic.repository.MemberRelationRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 删除旧关系Stage
 * 负责在保存新关系前，删除该人脸的旧数据关系
 *
 * 职责:
 * 1. 删除member_source中该人脸的未购买关系
 * 2. 删除member_video中该人脸的未购买关系
 * 3. 清除缓存
 */
@Slf4j
@Component
@StageConfig(
    stageId = "delete_old_relations",
    optionalMode = StageOptionalMode.FORCE_ON,
    description = "删除人脸旧关系数据"
)
public class DeleteOldRelationsStage extends AbstractPipelineStage<FaceMatchingContext> {

    @Autowired
    private SourceMapper sourceMapper;

    @Autowired
    private VideoMapper videoMapper;

    @Autowired
    private MemberRelationRepository memberRelationRepository;

    @Autowired
    private com.ycwl.basic.biz.FaceStatusManager faceStatusManager;

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

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

        try {
            log.debug("删除人脸旧关系数据：faceId={}, memberId={}", faceId, memberId);

            // 1. 删除member_source中的未购买关系
            sourceMapper.deleteNotBuyFaceRelation(memberId, faceId);

            // 2. 删除member_video中的未购买关系
            videoMapper.deleteNotBuyFaceRelations(memberId, faceId);

            // 3. 清除缓存
            memberRelationRepository.clearSCacheByFace(faceId);
            faceStatusManager.invalidatePuzzleSourceVersion(faceId);

            log.debug("人脸旧关系数据删除完成：faceId={}", faceId);

            return StageResult.success("旧关系数据已删除");

        } catch (Exception e) {
            log.error("删除旧关系数据失败，faceId={}", faceId, e);
            // 删除失败不影响主流程，返回降级
            return StageResult.degraded("删除旧关系数据失败: " + e.getMessage());
        }
    }
}
