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.common.result.SuperAgentTaskResultInfrastructureInputErrorResponse;
import cn.nianxx.thhotel.integrations.ai.superagent.service.impl.SuperAgentTaskResultException;
import cn.nianxx.thhotel.platform.hotel.service.HotelContextException;
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<?> handleIntakeException(
            ReservationAiTaskIntakeException exception) {
        if ("MISSING_SOURCE_MESSAGE_ID".equals(exception.getErrorCode())) {
            return ResponseEntity.status(exception.getStatus())
                    .body(new SuperAgentTaskResultInfrastructureInputErrorResponse(
                            "infrastructure_input_error",
                            "missing_source_message_id",
                            true,
                            List.of("source_message.source_message_id")));
        }
        return ResponseEntity.status(exception.getStatus())
                .body(error(exception.getErrorCode(), exception.getMessage()));
    }

    /**
     * 处理系统酒店缺失、多 ACTIVE 酒店或酒店访问受限等上下文异常。
     */
    @ExceptionHandler(HotelContextException.class)
    public ResponseEntity<SuperAgentTaskResultErrorResponse> handleHotelContextException(
            HotelContextException 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());
    }
}
