package com.bio.bio_backend.global.exception;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.bind.MethodArgumentNotValidException;

import com.bio.bio_backend.global.dto.ApiResponseDto;
import com.bio.bio_backend.global.constants.ApiResponseCode;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import lombok.extern.slf4j.Slf4j;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(ApiException.class)
    public ResponseEntity<ApiResponseDto<Void>> handleApiException(ApiException e) {
        ApiResponseDto<Void> response = ApiResponseDto.fail(e.getResponseCode());
        return ResponseEntity.status(e.getResponseCode().getStatusCode()).body(response);
    }
    
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<ApiResponseDto<Object>> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        // 검증 실패한 필드들의 상세 오류 정보 추출
        var errors = e.getBindingResult().getFieldErrors().stream()
            .map(error -> new ValidationError(error.getField(), error.getDefaultMessage()))
            .toList();
        
        ApiResponseDto<Object> response = ApiResponseDto.fail(ApiResponseCode.COMMON_ARGUMENT_NOT_VALID, errors);
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
    }

    // 검증 오류 상세 정보를 위한 내부 클래스
    private record ValidationError(String field, String message) {}

    @ExceptionHandler(Exception.class)
    public ResponseEntity<ApiResponseDto<Void>> handleException(Exception e) {
        log.error("Unexpected error occurred", e);
        
        ApiResponseDto<Void> response = ApiResponseDto.fail(ApiResponseCode.COMMON_INTERNAL_SERVER_ERROR);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
    }
}
