package kr.co.accura.wbx.spring.approval;

import kr.co.accura.wbx.spring.common.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 결재 핸들러 레지스트리 — Spring이 모든 ApprovalHandler 구현체를 자동 수집
 */
@Slf4j
@Component
public class ApprovalHandlerRegistry {

    private final Map<String, ApprovalHandler> handlers;

    @Autowired
    public ApprovalHandlerRegistry(List<ApprovalHandler> handlerList) {
        this.handlers = handlerList.stream()
                .collect(Collectors.toMap(ApprovalHandler::getTypeKey, Function.identity()));
        log.info("Registered approval handlers: {}", handlers.keySet());
    }

    public ApprovalHandler get(String typeKey) {
        return Optional.ofNullable(handlers.get(typeKey))
                .orElseThrow(() -> new BusinessException("Unknown approval type: " + typeKey));
    }

    public Collection<ApprovalHandler> getAll() {
        return handlers.values();
    }

    public boolean hasHandler(String typeKey) {
        return handlers.containsKey(typeKey);
    }
}
