import { notFound } from "next/navigation";

export enum FileType {
  MDX = "mdx",
  JSON = "json",
}

export async function fetchTinaData<T, V>(
  queryFunction: (
    variables?: V,
    options?: unknown
  ) => Promise<{
    data: T;
    variables: V;
    query: string;
  }>,
  filename?: string,
  type: FileType = FileType.MDX
): Promise<{ data: T; variables: V; query: string }> {
  try {
    const variables: V = {
      relativePath: filename ? `${filename}.${type}` : "",
    } as V;

    const response = await queryFunction(variables);

    // Ensure all data is plain objects (databaseClient may return
    // objects with null prototypes that can't be passed to Client Components)
    return JSON.parse(JSON.stringify(response));
  } catch {
    notFound();
  }
}
