package com.nisemoe.nise.config

import jakarta.servlet.*
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import org.springframework.beans.factory.annotation.Value
import org.springframework.security.web.header.HeaderWriterFilter

class CustomCorsFilter : Filter {

    @Value("\${ORIGIN:http://localhost:4200}")
    private lateinit var origin: String

    @Value("\${REPLAY_ORIGIN:http://localhost:5173}")
    private lateinit var replayOrigin: String

    override fun init(filterConfig: FilterConfig) {
        // We don't really need to do anything special here.
    }

    override fun doFilter(servletRequest: ServletRequest, servletResponse: ServletResponse, filterChain: FilterChain) {
        val response = servletResponse as HttpServletResponse
        val request = servletRequest as HttpServletRequest

        if(response.containsHeader("X-NISE-REPLAY") || request.getHeader("origin") == replayOrigin) {
            response.setHeader("Access-Control-Allow-Origin", replayOrigin)
            response.setHeader("Access-Control-Allow-Methods", "GET")
            response.setHeader(
                "Access-Control-Allow-Headers",
                "Access-Control-Allow-Headers, Origin,Accept, X-NISE-REPLAY, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers"
            )
            filterChain.doFilter(servletRequest, servletResponse)
            return
        }

        response.setHeader("Access-Control-Allow-Origin", origin)
        response.setHeader("Access-Control-Allow-Methods", "GET,POST,DELETE,PUT,OPTIONS,PATCH")
        response.setHeader(
            "Access-Control-Allow-Headers",
            "Access-Control-Allow-Headers, Origin,Accept, X-NISE-API, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers"
        )
        response.setHeader("Access-Control-Allow-Credentials", "true")
        filterChain.doFilter(servletRequest, servletResponse)
    }

    override fun destroy() {
        // We don't really need to do anything special here.
    }
}