package com.fzm.mall.customer.service.config.exception;

import com.fzm.mall.customer.service.repo.ResponseFactory;
import com.fzm.mall.customer.service.repo.ResponseVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.validation.ConstraintViolationException;

@ControllerAdvice
@ResponseBody
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Slf4j
public class ControllerExceptionHandler {

    private final ResponseFactory res;

    /*@ExceptionHandler(IllegalArgumentException.class)
    @ResponseStatus(HttpStatus.OK)
    public ResponseObject handleIllegalArgumentException() {
        return resf.getFailureResponse(ResCode.PARAM_ERROR);
    }

    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.OK)
    public ResponseObject handleRuntimeException(RuntimeException e) {
        String errMsg = e.getMessage();
        if (dbErrCodeArr.contains(errMsg)) {
            return resf.getFailureResponse(errMsg);
        }
        log.error(e.getMessage(), e);
        e.printStackTrace();
        return resf.getSimpleFailureResponse();
    }
    */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.OK)
    public ResponseVO<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        return res.getResponse(e.getBindingResult().getFieldError().getDefaultMessage());
    }

    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.OK)
    public ResponseVO<String> handleConstraintViolationException(ConstraintViolationException e) {
        return res.getResponse(e.getConstraintViolations().iterator().next().getMessageTemplate());
    }


    @ExceptionHandler(MyException.class)
    @ResponseStatus(HttpStatus.OK)
    public ResponseVO<String> handleMyException(MyException e) {
        return res.getResponse(e.getCode());
    }

}
