package com.interplug.qcast.config.Exception;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
  @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
  protected ResponseEntity<ErrorResponse> handle(HttpRequestMethodNotSupportedException e) {
    return ResponseEntity.badRequest()
        .body(ErrorResponse.of(ErrorCode.METHOD_NOT_ALLOWED.getMessage()));
  }

  @ExceptionHandler(BaseException.class)
  protected ResponseEntity<ErrorResponse> handle(BaseException e) {
    final ErrorCode errorCode = e.getErrorCode();
    return ResponseEntity.status(errorCode.getStatus())
        .body(ErrorResponse.of(errorCode.getMessage()));
  }

  @ExceptionHandler(QcastException.class)
  protected ResponseEntity<ErrorResponse> handle(QcastException e) {
    final ErrorCode errorCode = e.getErrorCode();
    if (e.getMessage() == null) {
      return ResponseEntity.status(errorCode.getStatus())
          .body(ErrorResponse.of(errorCode.getMessage()));
    }
    return ResponseEntity.status(errorCode.getStatus()).body(ErrorResponse.of(e.getMessage()));
  }

  @ExceptionHandler(Exception.class)
  protected ResponseEntity<ErrorResponse> handle(Exception e) {
    return ResponseEntity.internalServerError()
        .body(ErrorResponse.of(ErrorCode.INTERNAL_SERVER_ERROR.getMessage()));
  }
}
