package com.fs.audit.chain.handler;

import cn.hutool.core.util.ObjectUtil;
import com.fs.audit.chain.AbstractAuditHandler;
import com.fs.audit.chain.AuditContext;
import com.fs.audit.chain.AuditResult;
import com.fs.audit.dto.TemplateStepDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * 权限校验处理器
 * 校验当前用户是否有权限审核
 */
@Slf4j
@Component
@Order(1)
public class PermissionValidateHandler extends AbstractAuditHandler {

    @Override
    protected AuditResult doHandle(AuditContext context) {
        log.info("执行权限校验处理器");

        Long userId = context.getUserId();
        TemplateStepDTO stepConfig = context.getCurrentStepConfig();

        if (stepConfig == null) {
            return AuditResult.fail("当前步骤配置不存在");
        }

        // 校验用户是否在当前步骤的审核人列表中
        if (!stepConfig.getAuditUserIds().contains(userId) && ObjectUtil.equal(context.getUserType(),0)) {
            log.warn("用户{}无权审核，当前步骤审核人: {}", userId, stepConfig.getAuditUserIds());
            return AuditResult.fail("您没有权限审核此任务");
        }

        log.info("权限校验通过，用户: {} 用户类型: {}", userId, context.getUserType());
        return AuditResult.success("权限校验通过");
    }

    @Override
    public int getOrder() {
        return 1;
    }
}

