package com.spring.infra.security.handler;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import org.springframework.web.util.ServletRequestPathUtils;

import lombok.RequiredArgsConstructor;

@Component
@RequiredArgsConstructor
public class HttpRequestEndpointChecker {
    
    @Qualifier("requestMappingHandlerMapping")
    private final RequestMappingHandlerMapping requestMapping;

    public boolean isEndpointExist(HttpServletRequest request) {
        try {
            if (!ServletRequestPathUtils.hasParsedRequestPath(request)) {
                ServletRequestPathUtils.parseAndCache(request);
            }
            HandlerExecutionChain handler = requestMapping.getHandler(request);
            if (handler != null) {
                HandlerMethod method = (HandlerMethod) handler.getHandler();
                if (method != null) return true;
            }
        } catch (Exception e) {
            return false;
        }
        return false;
    }

}
