import { createClient } from "@sanity/client";

// Public, read-only. Content is fetched at build/ISR time. Page-level
// `export const revalidate` controls how often it refreshes.
export const sanity = createClient({
  projectId: "lrlnd56q",
  dataset: "production",
  apiVersion: "2024-01-01",
  useCdn: true,
});

/**
 * Fetch a single document, returning null on any failure so pages fall back to
 * their built-in defaults (a Sanity outage can never blank or break the site).
 */
export async function getDoc<T>(query: string, params: Record<string, unknown> = {}): Promise<T | null> {
  try {
    return await sanity.fetch<T>(query, params);
  } catch (err) {
    console.error("Sanity fetch failed:", err);
    return null;
  }
}

// GROQ snippet: resolve a `figure` field to a plain URL string
// (uploaded image if present, else the original path). Usage: fig("aboutPhoto").
export const fig = (field: string) => `"${field}": coalesce(${field}.image.asset->url, ${field}.legacyPath)`;

// Same, for an array of figures → array of URL strings.
export const figArray = (field: string) =>
  `"${field}": ${field}[]{ "u": coalesce(image.asset->url, legacyPath) }.u`;
