import { QueryClient, QueryFunction } from "@tanstack/react-query";

const ENV_API_BASE_URL = ((import.meta as any).env?.VITE_API_BASE_URL as string | undefined)?.trim();
const IS_LOCALHOST =
  typeof window !== "undefined" &&
  (window.location.hostname === "localhost" || window.location.hostname === "127.0.0.1");
const API_BASE_URL = (ENV_API_BASE_URL || (IS_LOCALHOST ? "http://localhost:8000" : "https://api.quantfortune.com"))
  .replace(/\/+$/, "")
  .replace(/\/api$/, "");
const REQUEST_TIMEOUT_MS = 12000;

function truncateText(value: string, maxLength = 180) {
  return value.length > maxLength ? `${value.slice(0, maxLength - 3)}...` : value;
}

function looksLikeHtml(value: string) {
  return /<!doctype html|<html[\s>]|<head[\s>]|<body[\s>]/i.test(value);
}

function normalizeApiPath(url: string) {
  const parsed = new URL(url, "https://frontend.local");
  const pathname = parsed.pathname.startsWith("/api")
    ? parsed.pathname
    : `/api${parsed.pathname.startsWith("/") ? parsed.pathname : `/${parsed.pathname}`}`;

  return `${pathname}${parsed.search}${parsed.hash}`;
}

export function resolveApiUrl(url: string) {
  if (url.startsWith("http://") || url.startsWith("https://")) {
    return url;
  }
  const normalizedPath = normalizeApiPath(url);
  if (!API_BASE_URL) {
    return normalizedPath;
  }
  return `${API_BASE_URL}${normalizedPath}`;
}

async function getResponseErrorMessage(res: Response) {
  const contentType = res.headers.get("content-type") || "";

  if (contentType.includes("application/json")) {
    try {
      const data = await res.json();
      const structuredDetail = typeof data?.detail === "object" && data?.detail !== null ? data.detail : null;
      const detail =
        (typeof data?.detail === "string" && data.detail) ||
        (typeof structuredDetail?.message === "string" && structuredDetail.message) ||
        (typeof structuredDetail?.detail === "string" && structuredDetail.detail) ||
        (typeof data?.message === "string" && data.message) ||
        (typeof data?.error === "string" && data.error);
      if (detail) {
        return `${res.status}: ${detail}`;
      }
    } catch {
      // Fall back to response text below.
    }
  }

  const text = ((await res.text()) || res.statusText).trim();
  if (!text) {
    return `${res.status}: ${res.statusText}`;
  }
  if (looksLikeHtml(text)) {
    return `${res.status}: Unexpected HTML response from the API. Check backend routing or deployment config.`;
  }

  return `${res.status}: ${truncateText(text.replace(/\s+/g, " "))}`;
}

async function throwIfResNotOk(res: Response) {
  if (!res.ok) {
    throw new Error(await getResponseErrorMessage(res));
  }
}

async function throwIfUnexpectedApiPayload(res: Response) {
  if (res.status === 204) {
    return;
  }

  const contentType = (res.headers.get("content-type") || "").toLowerCase();
  if (contentType.includes("application/json")) {
    return;
  }

  const body = (await res.clone().text()).trim();
  if (!body) {
    return;
  }
  if (body.startsWith("{") || body.startsWith("[")) {
    return;
  }
  if (looksLikeHtml(body)) {
    throw new Error("Unexpected HTML response from the API. Check backend routing or deployment config.");
  }
}

async function fetchWithTimeout(input: RequestInfo | URL, init?: RequestInit) {
  const controller = new AbortController();
  const timeoutId = globalThis.setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);

  try {
    return await fetch(input, {
      ...init,
      signal: controller.signal,
    });
  } catch (error) {
    if (error instanceof DOMException && error.name === "AbortError") {
      throw new Error("Request timed out. Please try again.");
    }
    throw error;
  } finally {
    globalThis.clearTimeout(timeoutId);
  }
}

export async function apiRequest(
  method: string,
  url: string,
  data?: unknown | undefined,
): Promise<Response> {
  const res = await fetchWithTimeout(resolveApiUrl(url), {
    method,
    headers: {
      Accept: "application/json",
      ...(data ? { "Content-Type": "application/json" } : {}),
    },
    body: data ? JSON.stringify(data) : undefined,
    credentials: "include",
  });

  await throwIfResNotOk(res);
  await throwIfUnexpectedApiPayload(res);
  return res;
}

type UnauthorizedBehavior = "returnNull" | "throw";
export const getQueryFn: <T>(options: {
  on401: UnauthorizedBehavior;
}) => QueryFunction<T> =
  ({ on401: unauthorizedBehavior }) =>
  async ({ queryKey }) => {
    const res = await fetchWithTimeout(resolveApiUrl(queryKey.join("/") as string), {
      headers: {
        Accept: "application/json",
      },
      credentials: "include",
    });

    if (unauthorizedBehavior === "returnNull" && res.status === 401) {
      return null;
    }

    await throwIfResNotOk(res);
    await throwIfUnexpectedApiPayload(res);
    return await res.json();
  };

export const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      queryFn: getQueryFn({ on401: "throw" }),
      refetchInterval: false,
      refetchOnWindowFocus: false,
      staleTime: 5_000,
      retry: false,
    },
    mutations: {
      retry: false,
    },
  },
});
