package com.caliverse.admin.global.common.exception;

import com.caliverse.admin.domain.response.ExceptionResponse;
import com.caliverse.admin.global.common.code.CommonCode;
import com.caliverse.admin.global.common.code.ErrorCode;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

//전체 서비스단의 exception을 캐치
@ControllerAdvice
public class GlobalException extends ResponseEntityExceptionHandler {
    @ExceptionHandler
    public ResponseEntity<ExceptionResponse> handleException(RestApiException restApiException){
        return ResponseEntity.ok().body(
                ExceptionResponse.builder()
                        .result(CommonCode.ERROR.getResult())
                        .status(restApiException.getStatusCode())
                        .data(ExceptionResponse.ExceptionData.builder().message(restApiException.getMessage()).build())
                        .build()
        );
    }

    // 토큰 없을경우 exception 캐치하여 응답한다
    @ExceptionHandler(AuthenticationException.class)
    public ResponseEntity<ExceptionResponse> authenticationException(AuthenticationException authenticationException){
        return ResponseEntity.ok().body(
                ExceptionResponse.builder()
                        .result(CommonCode.ERROR.getResult())
                        .status(HttpServletResponse.SC_UNAUTHORIZED)
                        .data(ExceptionResponse.ExceptionData.builder().message(ErrorCode.WRONG_TYPE_TOKEN.getMessage()).build())
                        .build()
        );
    }

    //전체 exception 처리
    @ExceptionHandler(Exception.class)
    public ResponseEntity<ExceptionResponse> exceptionAll(Exception exception){
        return ResponseEntity.ok().body(
                ExceptionResponse.builder()
                        .result(CommonCode.ERROR.getResult())
                        .status(CommonCode.ERROR.getHttpStatus())
                        .data(ExceptionResponse.ExceptionData.builder().message(exception.getMessage()).build())
                        .build()
        );
    }
}
