package com.example.api;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import com.example.domain.ErrorResponse;

@RestControllerAdvice
public class ControllerExceptionHandler extends ResponseEntityExceptionHandler{

	@Override
	protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers, HttpStatus status, WebRequest request) {
	    if (!(body instanceof ErrorResponse)) {
	    	if(status.getReasonPhrase().equalsIgnoreCase("Method Not Allowed")){
	    		body = new Error("URLの誤り");
	    		status = HttpStatus.NOT_FOUND;
	    	}
	    }
	    return new ResponseEntity<>(body, headers, status);
	}
	
	@ExceptionHandler({Exception.class})
	public ResponseEntity<Object> handle400(Exception ex, WebRequest request) {
	    HttpHeaders headers = new HttpHeaders();
	    ErrorResponse body = new ErrorResponse("これ以上購入できません");
	    HttpStatus status = HttpStatus.BAD_REQUEST;

	    return this.handleExceptionInternal(ex, body, headers, status, request);
	}
}