package me.qwq.doghouse.controller.common;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.error.ErrorAttributeOptions.Include;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.request.WebRequest;

import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.http.HttpServletRequest;
import me.qwq.doghouse.service.ThemeService;

import java.util.Map;

@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class ErrorPageController implements ErrorController {

    @Autowired
    ErrorAttributes errorAttributes;
    
    @Autowired
    ThemeService themeService;

    @RequestMapping(produces = MediaType.TEXT_HTML_VALUE)
    public String errorHtml(HttpServletRequest request) {
        HttpStatus status = getStatus(request);
        return themeService.getCurrentTheme().getErrorTemplateString(status);
    }

    @ResponseBody
    @RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        boolean include = Boolean.parseBoolean(request.getParameter("trace"));
        ErrorAttributeOptions options = ErrorAttributeOptions.defaults();
        if (include) {
            options = options.including(Include.STACK_TRACE);
        }

        WebRequest webRequest = new ServletWebRequest(request);
        Map<String, Object> body = errorAttributes.getErrorAttributes(webRequest, options);

        return ResponseEntity.status(getStatus(request)).body(body);
    }

    private HttpStatus getStatus(HttpServletRequest request) {
        Object value = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
        if (value instanceof Integer code) {
            HttpStatus status = HttpStatus.resolve(code);
            return (status != null ? status : HttpStatus.INTERNAL_SERVER_ERROR);
        }
        return HttpStatus.INTERNAL_SERVER_ERROR;
    }
}
