package ee.tuleva.onboarding.config;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

@Slf4j
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CORSFilter extends GenericFilterBean {

  String DEFAULT_ALLOWED_ORIGIN = "https://pension.tuleva.ee";
  private List<String> allowedOrigins = Arrays.asList(DEFAULT_ALLOWED_ORIGIN, "https://tuleva.ee");

  @Override
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
      throws IOException, ServletException {
    HttpServletResponse response = (HttpServletResponse) res;
    HttpServletRequest request = (HttpServletRequest) req;
    String origin = request.getHeader("Origin");
    String allowedOriginResponse =
        allowedOrigins.contains(origin) ? origin : DEFAULT_ALLOWED_ORIGIN;
    response.setHeader("Access-Control-Allow-Origin", allowedOriginResponse);
    response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "Authorization");
    response.setHeader("Access-Control-Allow-Credentials", "true");
    response.setHeader(
        "P3P",
        "CP=\"ALL IND DSP COR ADM CONo CUR CUSo IVAo IVDo PSA PSD TAI TELo OUR SAMo CNT COM INT NAV ONL PHY PRE PUR UNI\"");

    List<String> allowedHeaders =
        Arrays.asList(
            "x-requested-with",
            "x-statistics-identifier",
            HttpHeaders.CONTENT_TYPE,
            HttpHeaders.AUTHORIZATION,
            HttpHeaders.USER_AGENT,
            HttpHeaders.ORIGIN,
            HttpHeaders.ACCEPT);
    response.setHeader("Access-Control-Allow-Headers", String.join(", ", allowedHeaders));

    if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
      response.setStatus(HttpServletResponse.SC_OK);
    } else {
      chain.doFilter(req, res);
    }
  }
}

@@ -804,16 +804,22 @@
 private 
+final 
 List%3CStr
@@ -839,16 +839,22 @@
 rigins =
+%0A     
  Arrays.
@@ -883,16 +883,45 @@
 _ORIGIN,
+ %22https://staging.tuleva.ee%22,
  %22https:

Add staging to cors filter