package llc.arma.fleet.monitor.security

import jakarta.servlet.FilterChain
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
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

@Component
class DemoTokenAuthFilter(
    private val tokenStore: AuthTokenStore,
) : OncePerRequestFilter() {
    override fun doFilterInternal(
        request: HttpServletRequest,
        response: HttpServletResponse,
        filterChain: FilterChain,
    ) {
        val token = request.getHeader("Authorization")
            ?.removePrefix("Bearer ")
            ?: request.cookies?.firstOrNull { it.name == "Access-token" }?.value

        val userId = tokenStore.resolveUserId(token)
        if (userId != null) {
            SecurityContextHolder.getContext().authentication = UsernamePasswordAuthenticationToken(
                userId.toString(),
                null,
                listOf(SimpleGrantedAuthority("AUTHENTICATED")),
            )
        }

        filterChain.doFilter(request, response)
    }
}
