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

import com.eactive.apim.portal.portalproperty.service.PortalPropertyService;
import java.io.IOException;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@Slf4j
public class ApiKeyInterceptor implements HandlerInterceptor {

    private static final String API_KEY_HEADER = "X-API-KEY";
    private static final String PORTAL_PROPERTY_GROUP = "Portal";

    @Autowired
    private PortalPropertyService portalPropertyService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            String requestApiKey = request.getHeader(API_KEY_HEADER);

            if (StringUtils.isEmpty(requestApiKey)) {
                log.warn("Request received without API key. URI: {}", request.getRequestURI());
                sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "API key is missing");
                return false;
            }

            Map<String, String> properties = portalPropertyService.getPortalPropertiesAsMap(PORTAL_PROPERTY_GROUP);
            String validApiKey = properties.get("apiKey");

            if (StringUtils.isEmpty(validApiKey)) {
                log.error("API key not configured in properties");
                sendErrorResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "API key is not configured");
                return false;
            }

            if (!validApiKey.equals(requestApiKey)) {
                log.warn("Invalid API key received. URI: {}", request.getRequestURI());
                sendErrorResponse(response, HttpServletResponse.SC_FORBIDDEN, "Invalid API key");
                return false;
            }

            return true;

        } catch (Exception e) {
            log.error("Error processing API key validation", e);
            sendErrorResponse(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error processing request");
            return false;
        }
    }

    private void sendErrorResponse(HttpServletResponse response, int status, String message) throws IOException {
        response.setStatus(status);
        response.setContentType("application/json");
        response.getWriter().write(String.format("{\"error\": \"%s\"}", message));
    }
}
