package com.fs.audit.chain;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Comparator;
import java.util.List;

/**
 * 审核责任链构建器
 * 负责构建和管理审核处理器链
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class AuditChainBuilder {

    private final List<AuditHandler> handlers;

    private AuditHandler chainHead;

    @PostConstruct
    public void init() {
        buildChain();
    }

    /**
     * 构建责任链
     */
    private void buildChain() {
        if (handlers == null || handlers.isEmpty()) {
            log.warn("没有找到审核处理器");
            return;
        }

        // 按顺序排序
        handlers.sort(Comparator.comparingInt(AuditHandler::getOrder));

        // 构建链
        for (int i = 0; i < handlers.size() - 1; i++) {
            handlers.get(i).setNext(handlers.get(i + 1));
        }

        chainHead = handlers.get(0);

        log.info("审核责任链构建完成，处理器数量: {}", handlers.size());
        handlers.forEach(h -> log.info("  - {} (order: {})", h.getClass().getSimpleName(), h.getOrder()));
    }

    /**
     * 执行审核流程
     */
    public AuditResult execute(AuditContext context) {
        if (chainHead == null) {
            return AuditResult.fail("审核处理链未初始化");
        }
        return chainHead.handle(context);
    }
}

