package de.htwsaar.webshop.controller;

import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import static de.htwsaar.webshop.config.ControllerPathConfig.ERROR;


/**
 * Controller for handling application errors.
 * This class implements the {@link org.springframework.boot.web.servlet.error.ErrorController}
 * interface to provide custom error responses for the application.
 * <p>
 * It uses predefined templates to replace placeholders with actual error details
 * such as the error code, name, and timestamp.
 * </p>
 */
@RestController
@Slf4j
public class ErrorController implements org.springframework.boot.web.servlet.error.ErrorController {

    /**
     * Handles error responses for the application.
     *
     * @param request the HTTP servlet request containing error details.
     * @return a {@link ResponseEntity} containing the formatted error {@link Resource}.
     */
    @RequestMapping(ERROR)
    public ResponseEntity<String> error(HttpServletRequest request) {
        log.info("Request Error on: {}", request.getRequestURI());

        // get Error Code & Name
        Object errorCodeUnCast = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
        int errorCode;
        if (errorCodeUnCast == null) {
            errorCode = 404;
            log.info("[{}:error()] direct request to error page! Using default errorCode '{}'",
                    ErrorController.class.getSimpleName(), errorCode);
        } else {
            errorCode = (Integer) errorCodeUnCast;
        }

        Object errorNameUnCast = request.getAttribute(RequestDispatcher.ERROR_MESSAGE);
        String errorName;
        if (errorNameUnCast == null) {
            errorName = "Not Found";
            log.info("[{}:error()] direct request to error page! Using default errorName '{}'",
                    ErrorController.class.getSimpleName(), errorName);
        } else {
            errorName = (String) errorNameUnCast;
        }

        log.warn("[{}] ErrorCode: {}, ErrorName: {}", request.getRequestURI(), errorCode, errorName);

        //replace
        return ResponseEntity.status(errorCode).body(errorName);
    }
}
