package com.zioinfo.hrm.common;

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

/**
 * 전역 예외 핸들러 — 스택트레이스 미노출, 에러 코드만 반환.
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(RuntimeException.class)
    public ResponseEntity<ApiResponse<Void>> handleRuntime(RuntimeException e) {
        String msg = e.getMessage();
        log.warn("HRM Runtime: {}", msg);
        if (msg != null && msg.startsWith("ERR-HRM-403")) {
            return ResponseEntity.status(HttpStatus.FORBIDDEN).body(ApiResponse.fail(msg));
        }
        if (msg != null && msg.startsWith("ERR-AUTH")) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(ApiResponse.fail(msg));
        }
        return ResponseEntity.badRequest().body(ApiResponse.fail(msg != null ? msg : "ERR-HRM-500"));
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<ApiResponse<Void>> handleAll(Exception e) {
        log.error("HRM Unexpected", e);
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
            .body(ApiResponse.fail("ERR-HRM-500: 서버 오류가 발생했습니다"));
    }
}
