import { getApiBaseUrl } from "@/components/main/BaseUrl";

type FetchApiJsonResult<T> = {
  ok: boolean;
  status: number;
  data: T | null;
};

export async function fetchApiJson<T>(
  path: string,
  options?: RequestInit
): Promise<FetchApiJsonResult<T>> {
  const normalizedPath = path.startsWith("/") ? path : `/${path}`;
  const url = `${getApiBaseUrl()}${normalizedPath}`;

  try {
    const response = await fetch(url, {
      cache: "no-store",
      ...options,
    });

    const contentType = response.headers.get("content-type") || "";
    if (!contentType.includes("application/json")) {
      return { ok: false, status: response.status, data: null };
    }

    const data = (await response.json()) as T;
    return { ok: response.ok, status: response.status, data };
  } catch {
    return { ok: false, status: 0, data: null };
  }
}
