package cn.nianxx.thhotel.integrations.ai.superagent.control;

import cn.nianxx.thhotel.integrations.ai.superagent.common.result.SuperAgentTaskResultErrorResponse;
import cn.nianxx.thhotel.integrations.ai.superagent.service.impl.SuperAgentTaskResultException;
import cn.nianxx.thhotel.workflows.reservation.service.impl.ReservationAiTaskIntakeException;
import java.util.List;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * SuperAgent 任务结果入站统一异常处理。错误响应只返回安全错误码和简短说明。
 */
@RestControllerAdvice(assignableTypes = SuperAgentTaskResultController.class)
public class SuperAgentTaskResultControllerAdvice {

    /**
     * 处理 SuperAgent 鉴权、请求大小等协议层受控异常。
     */
    @ExceptionHandler(SuperAgentTaskResultException.class)
    public ResponseEntity<SuperAgentTaskResultErrorResponse> handleSecurityException(
            SuperAgentTaskResultException exception) {
        return ResponseEntity.status(exception.getStatus())
                .body(error(exception.getErrorCode(), exception.getMessage()));
    }

    /**
     * 处理 Reservation 接收阶段的 SourceMessage、幂等和 AI item 技术校验异常。
     */
    @ExceptionHandler(ReservationAiTaskIntakeException.class)
    public ResponseEntity<SuperAgentTaskResultErrorResponse> handleIntakeException(
            ReservationAiTaskIntakeException exception) {
        return ResponseEntity.status(exception.getStatus())
                .body(error(exception.getErrorCode(), exception.getMessage()));
    }

    /**
     * 构建统一错误响应，第一版不回显 request_id，避免异常路径暴露未经校验的外部输入。
     */
    private SuperAgentTaskResultErrorResponse error(String errorCode, String message) {
        return new SuperAgentTaskResultErrorResponse(null, errorCode, message, List.of());
    }
}
