package com.eactive.eai.rms.common.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.Map;

/**
 * 서버 시작 시 등록된 HTTP 엔드포인트 목록을 로그로 출력
 */
@Component
public class EndpointLogger implements ApplicationListener<ContextRefreshedEvent> {

    private static final Logger log = LoggerFactory.getLogger(EndpointLogger.class);

    private boolean logged = false;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        // 중복 출력 방지 (parent/child context)
        if (logged) {
            return;
        }

        ApplicationContext ctx = event.getApplicationContext();

        try {
            RequestMappingHandlerMapping mapping = ctx.getBean(RequestMappingHandlerMapping.class);
            Map<RequestMappingInfo, HandlerMethod> methods = mapping.getHandlerMethods();

            log.debug("========== Registered HTTP Endpoints ({}) ==========", methods.size());

            methods.entrySet().stream()
                    .sorted((e1, e2) -> e1.getKey().toString().compareTo(e2.getKey().toString()))
                    .forEach(entry -> { 
                        RequestMappingInfo info = entry.getKey();
                        HandlerMethod method = entry.getValue();
                        log.debug("{} -> {}.{}",
                                info.getPatternsCondition(),
                                method.getBeanType().getSimpleName(),
                                method.getMethod().getName());
                    });

            log.debug("========== End of Endpoints ==========");
            logged = true;

        } catch (Exception e) {
            log.warn("Failed to log endpoints: {}", e.getMessage());
        }
    }
}
