import {
  getStorefrontRouteUrl,
  getWooStoreApiUrl,
  getWordPressRestApiUrl,
} from "@/lib/config";

async function parseJsonResponse<T>(response: Response, errorPrefix: string) {
  if (!response.ok) {
    let message = `${errorPrefix}: ${response.status}`;

    try {
      const payload = (await response.json()) as { message?: string; code?: string };
      message = payload.message || payload.code || message;
    } catch {}

    throw new Error(message);
  }

  return (await response.json()) as T;
}

export async function starterRouteFetch<T>(
  path: string,
  init?: RequestInit,
): Promise<T> {
  const response = await fetch(getStorefrontRouteUrl(path), {
    ...init,
    headers: {
      Accept: "application/json",
      ...(init?.headers ?? {}),
    },
    next:
      init?.cache === "no-store"
        ? { revalidate: 0 }
        : { revalidate: 60 },
  });

  return parseJsonResponse<T>(response, `Starter route request failed for ${path}`);
}

export async function wooStoreFetch<T>(
  path: string,
  init?: RequestInit,
): Promise<T> {
  const response = await fetch(getWooStoreApiUrl(path), {
    ...init,
    headers: {
      Accept: "application/json",
      ...(init?.headers ?? {}),
    },
    cache: "no-store",
  });

  return parseJsonResponse<T>(response, `Woo Store request failed for ${path}`);
}

export async function wordpressRestFetch<T>(
  path: string,
  init?: RequestInit,
): Promise<T> {
  const response = await fetch(getWordPressRestApiUrl(path), {
    ...init,
    headers: {
      Accept: "application/json",
      ...(init?.headers ?? {}),
    },
    next:
      init?.cache === "no-store"
        ? { revalidate: 0 }
        : { revalidate: 300 },
  });

  return parseJsonResponse<T>(response, `WordPress REST request failed for ${path}`);
}
