import { createClient, createConfig } from "@/lib/api/client";
import type { ClientOptions as GeneratedClientOptions } from "@/lib/api/client";
import { getAuthToken } from "@/utils/token";

const getBaseUrl = () => {
  if (typeof window !== "undefined") return "";
  return process.env.API_BASE_URL || process.env.NEXT_PUBLIC_API_BASE_URL || "http://localhost:8000";
};

const requestInterceptor = async (request: Request) => {
  const headers = new Headers(request.headers);
  const token = getAuthToken();

  if (token && !headers.get("authorization")) {
    headers.set("authorization", `Bearer ${token}`);
  }
  headers.set("X-Requested-With", "XMLHttpRequest");
  headers.set("X-Client-Platform", "web");

  return new Request(request, {
    headers,
    signal: AbortSignal.timeout(120000)
  });
};

const responseInterceptor = async (response: Response) => response;

const errorInterceptor = async (error: unknown, response: Response, _request: Request, options: unknown) => {
  const status = response?.status;
  const suppressErrorToast = (options as { suppressErrorToast?: boolean } | undefined)?.suppressErrorToast === true;
  let message = "请求失败，请重试";

  try {
    const data = await response.clone().json();
    const responseMessage = typeof data?.message === "string" ? data.message : "";
    const responseDetail = typeof data?.detail === "string" ? data.detail : "";

    if (status && status >= 400 && status < 500) {
      // 4xx 优先使用后端 message 字段；若缺失则回退 detail，避免无提示。
      message = responseMessage || responseDetail || message;
    } else {
      message = responseMessage || responseDetail || message;
    }
  } catch {
    if (status === 401) message = "身份认证失败，请重新登录";
    if (status === 403) message = "权限不足，无法访问该资源";
    if (status && status >= 500) message = "服务器异常，请稍后重试";
  }

  if (status === 401 && typeof window !== "undefined") {
    localStorage.removeItem("user");
    const currentPath = window.location.pathname;
    if (!currentPath.startsWith("/login")) {
      window.location.href = `/login?redirect=${encodeURIComponent(currentPath)}`;
    }
  }

  if (!suppressErrorToast && typeof window !== "undefined") {
    const { toast } = await import("sonner");
    toast.error(message);
  }

  const enhancedError = new Error(message) as Error & { status?: number; data?: unknown };
  enhancedError.status = status;
  enhancedError.data = error;
  return enhancedError;
};

const baseConfig = createConfig<GeneratedClientOptions>({
  baseUrl: getBaseUrl(),
  fetch: typeof window !== "undefined" ? window.fetch.bind(window) : undefined
});

export const client = createClient(baseConfig);
client.interceptors.request.use(requestInterceptor);
client.interceptors.response.use(responseInterceptor);
client.interceptors.error.use(errorInterceptor);
