package com.sckw.gateway.utils;

import com.sckw.core.exception.BusinessPlatfromException;
import com.sckw.gateway.pojo.HttpResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.server.reactive.ServerHttpRequest;

/**
 * @desc: 网关异常处理工具类
 * @date: 2025-11-10
 */
@Slf4j
public class GatewayExceptionUtil {

    /**
     * 构建服务不可用响应
     */
    public static HttpResult buildServiceUnavailableResponse(ServerHttpRequest request, Throwable throwable) {
        String path = request.getPath().value();
        String method = request.getMethod().name();

        log.error("网关服务不可用异常: 路径={}, 方法={}, 异常信息={}", path, method, throwable.getMessage());

        // 根据异常类型返回不同的错误信息
        if (throwable instanceof org.springframework.cloud.gateway.support.NotFoundException) {
            return HttpResult.error(60500, "目标服务不存在或未启动");
        } else if (throwable instanceof org.springframework.cloud.gateway.support.TimeoutException) {
            return HttpResult.error(60500, "服务响应超时，请稍后重试");
        } else if (throwable instanceof org.springframework.web.server.ResponseStatusException) {
            org.springframework.web.server.ResponseStatusException statusException =
                    (org.springframework.web.server.ResponseStatusException) throwable;
            if (statusException.getStatusCode().value() == 503) {
                return HttpResult.error(60500, "服务请求异常，请稍后重试");
            }else{
                return HttpResult.error(60500, "服务请求异常，请稍后重试["+statusException.getStatusCode().value()+"]");
            }
        }

        // 默认返回服务不可用
        return HttpResult.error(60500, "服务请求异常，请稍后重试");
    }

    /**
     * 构建网关内部错误响应
     */
    public static HttpResult buildInternalErrorResponse(ServerHttpRequest request, Throwable throwable) {
        String path = request.getPath().value();
        String method = request.getMethod().name();

        log.error("网关内部错误: 路径={}, 方法={}, 异常信息={}", path, method, throwable.getMessage(), throwable);

        return HttpResult.error(60500, "网关内部错误，请联系管理员");
    }
}
