package com.cameleer.server.app.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

/**
 * Validates that all requests to data and agent endpoints include the
 * {@code X-Cameleer-Protocol-Version} header with value {@code "1"}.
 * <p>
 * Requests missing the header or using an unsupported version receive a 400 response
 * with a JSON error body.
 */
@Component
public class ProtocolVersionInterceptor implements HandlerInterceptor {

    private static final String HEADER_NAME = "X-Cameleer-Protocol-Version";
    private static final String SUPPORTED_VERSION = "1";

    private final ObjectMapper objectMapper;

    public ProtocolVersionInterceptor(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

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

        if (version == null || !SUPPORTED_VERSION.equals(version)) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            objectMapper.writeValue(response.getWriter(),
                    Map.of("error", "Missing or unsupported X-Cameleer-Protocol-Version header"));
            return false;
        }

        return true;
    }
}
