package kr.co.accura.wbx.spring.auth;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.List;

/**
 * API Key 인증 — 서버-서버(SAP BTP, ERP 등) 연동용
 * Header: X-API-Key: {key}
 */
@Slf4j
@Component
public class ApiKeyFilter extends OncePerRequestFilter {

    @Value("${wbx.spring.api-keys:}")
    private List<String> validApiKeys;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                     HttpServletResponse response,
                                     FilterChain chain) throws ServletException, IOException {
        String apiKey = request.getHeader("X-API-Key");
        if (apiKey != null && !apiKey.isBlank() && validApiKeys.contains(apiKey)) {
            var auth = new UsernamePasswordAuthenticationToken(
                    "system", null,
                    List.of(new SimpleGrantedAuthority("ROLE_SYSTEM"),
                            new SimpleGrantedAuthority("ROLE_SA")));
            SecurityContextHolder.getContext().setAuthentication(auth);
            log.debug("API Key authenticated: {}", apiKey.substring(0, Math.min(8, apiKey.length())) + "...");
        }
        chain.doFilter(request, response);
    }

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) {
        return request.getHeader("X-API-Key") == null;
    }
}
