package dev.sonpx.loyalty.mcp.aspect;

import dev.sonpx.loyalty.mcp.model.Result;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

/**
 * Global exception handler for @McpTool methods using AOP.
 * Prevents internal stack traces from leaking to the MCP Client.
 */
@Slf4j
@Aspect
@Component
public class GlobalToolExceptionHandlerAspect {

    @Around("@annotation(org.springframework.ai.mcp.annotation.McpTool)")
    public Object handleException(ProceedingJoinPoint pjp) throws Throwable {
        try {
            return pjp.proceed();
        } catch (Exception e) {
            log.error("Global AOP exception caught during execution of MCP tool {}: {}", pjp.getSignature().getName(), e.getMessage());
            // Return a safe Result to prevent stack traces from leaking to the agent
            return Result.of(null, "Lỗi hệ thống khi gọi tool tại MCP server. Không thể xử lý yêu cầu. Vui lòng báo cáo lỗi này.");
        }
    }
}
