package com.andr3h3nriqu3s.appliations

import org.springframework.context.annotation.Configuration
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer
import org.springframework.web.servlet.config.annotation.EnableWebMvc
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer
import org.springframework.web.servlet.config.annotation.CorsRegistry
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer
import org.springframework.web.servlet.mvc.Controller
import org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver
import org.springframework.web.method.HandlerTypePredicate
import org.springframework.web.bind.annotation.RestController
import org.springframework.http.MediaType
import org.springframework.stereotype.Component
import org.springframework.web.servlet.ModelAndView

import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse

import com.andr3h3nriqu3s.applications.NoToken
import com.andr3h3nriqu3s.applications.NotAuth
import com.andr3h3nriqu3s.applications.UserNotFound
import com.andr3h3nriqu3s.applications.NotFound
import com.andr3h3nriqu3s.applications.BadRequest

@Configuration
@EnableWebMvc
class WebConfig : WebMvcConfigurer {

    override public fun configureContentNegotiation(configurer: ContentNegotiationConfigurer){
        // configurer.defaultContentType( MediaType.APPLICATION_JSON );
        configurer.mediaType("json", MediaType.APPLICATION_JSON)
    }

    override public fun addCorsMappings(registry: CorsRegistry) {
    	registry.addMapping("*").allowedOrigins("*")
    }

}

@Component
public class RestResponseStatusExceptionResolver : AbstractHandlerExceptionResolver() {

	override protected fun doResolveException(
		requeset: HttpServletRequest,
      	response: HttpServletResponse,
       	handler: Any?,
        ex: Exception
	): ModelAndView? {
		try {
			if (ex is NoToken || ex is NotAuth || ex is UserNotFound) {
				response.sendError(HttpServletResponse.SC_FORBIDDEN)
				return ModelAndView()
			}
			if (ex is NotFound) {
				response.sendError(HttpServletResponse.SC_NOT_FOUND)
				return ModelAndView()
			}
			if (ex is BadRequest) {
				response.sendError(HttpServletResponse.SC_BAD_REQUEST)
				return ModelAndView()
			}
		} catch (handlerException: Exception) {
        	print("Faield to handle exception ")
         	print(handlerException)
            print("\n")
        }
        return null;
	}

}
