package ru.soune.nocopy.util;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Component
public class InternalApiFilter extends OncePerRequestFilter {

    @Value("${app.internal-api-key}")
    private String internalApiKey;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        if (request.getRequestURI().startsWith("api/internal/") ||
                request.getRequestURI().startsWith("api/internal/download")) {
            String providedKey = request.getHeader("X-Internal-Key");

            if (!internalApiKey.equals(providedKey)) {
                response.sendError(403, "Access Denied: Internal API only");
                return;
            }
        }

        filterChain.doFilter(request, response);
    }
}
