package com.tofly.base.exception;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.tofly.common.core.entity.ResultRespone;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.bind.BindException;
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 javax.validation.ConstraintViolationException;


@RestControllerAdvice
@Slf4j
@AllArgsConstructor
public class GlobalResponse {

    private final ObjectMapper objectMapper;

    @ExceptionHandler(value = BusinessException.class)
    public ResponseEntity<ResultRespone> exceptionHandler(BusinessException e) {
        String message = e.getMessage();
        log.info(message, e);
        return new ResponseEntity<>(ResultRespone.failed(message), HttpStatus.OK);
    }

    @ExceptionHandler(value = ConstraintViolationException.class)
    public ResponseEntity<ResultRespone> constraintViolationExceptionHandler(ConstraintViolationException e) {
        String message = e.getMessage();
        log.error(message, e);
        return new ResponseEntity<>(ResultRespone.failed(message), HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(value = BindException.class)
    public ResponseEntity<ResultRespone> bindExceptionHandler(BindException e) {
        String message = e.getMessage();
        log.error(message, e);
        return new ResponseEntity<>(ResultRespone.failed(message), HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(value = Exception.class)
    public ResponseEntity<ResultRespone> otherExceptionHandler(Exception e) {
        String message = e.getMessage();
        log.error(message, e);
        return new ResponseEntity<>(ResultRespone.failed(message), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
