package com.samsung.filter;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class CorsFilter extends OncePerRequestFilter {

    private static final String EXPOSE_HEADERS = "Cache-Control, Content-Language, Content-Type, Expires, Last-Modified, Pragma, Accept, Accept-Language, Content-Disposition, x-auth-token, page-id, menu-id, " +
            "Access-Control-Request-Headers, Origin, Referer, User-Agent, original-user-id, last-access-time, Date";

    @Value("${cors.domain:*}")
    private String domain;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        response.addHeader("Access-Control-Allow-Origin", domain);
        if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
            response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH");
            response.addHeader("Access-Control-Allow-Headers", EXPOSE_HEADERS);
            response.addHeader("Access-Control-Max-Age", "3600");
        }
        response.addHeader("Access-Control-Expose-Headers", EXPOSE_HEADERS);
        filterChain.doFilter(request, response);
    }
}
