package com.example.todolist.exception;

import java.util.Locale;

import org.springframework.context.MessageSource;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import lombok.RequiredArgsConstructor;

@ControllerAdvice
@RequiredArgsConstructor
public class GlobalViewExceptionHandler {

    private final MessageSource messageSource;

    @ExceptionHandler(ForbiddenException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public ModelAndView handleForbidden(ForbiddenException ex, Locale locale) {
        String message = messageSource.getMessage(
                ex.getMessageCode(),
                ex.getArgs(),
                ex.getMessageCode(), // 未定義時のフォールバック
                locale);

        ModelAndView mv = new ModelAndView();
        mv.setViewName("error/403");
        mv.addObject("message", message);
        return mv;
    }

    @ExceptionHandler(NotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ModelAndView handleNotFound(NotFoundException ex, Locale locale) {
        String message = messageSource.getMessage(
                ex.getMessageCode(),
                ex.getArgs(),
                ex.getMessageCode(),
                locale);

        ModelAndView mv = new ModelAndView();
        mv.setViewName("error/404");
        mv.addObject("message", message);
        return mv;
    }
}
