package dev.sonpx.loyalty.mcp.exception;

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;

/**
 * Global exception handler for the MCP Server.
 * Prevents stack traces from leaking to the MCP Client (Agent).
 */
@Slf4j
@RestControllerAdvice
public class GlobalMcpExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleException(Exception ex) {
        log.error("Global exception caught in MCP server: {}", ex.getMessage());
        // We return a safe error message instead of the HTML stack trace.
        // Returning a generic 500 error prevents the LLM from trying to explain server internals.
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("{\"error\": \"Lỗi hệ thống tại MCP Server. Không thể xử lý yêu cầu.\"}");
    }
}
