import "server-only";

import { createClient, type SanityClient } from "@sanity/client";

import { apiVersion, dataset, isConfigured, projectId, readToken } from "./env";

let cached: SanityClient | null = null;

/**
 * Returns a singleton Sanity read client. Throws if the environment is not
 * configured — callers on the RSC fetch path should check `isConfigured`
 * first and fall back to empty state without invoking this.
 *
 * Per @sanity/client guidance: `useCdn: true` when no token is present
 * (public CDN reads), `useCdn: false` when a token is present (so that
 * draft/private content is served from the live API, not the CDN).
 */
export function getClient(): SanityClient {
  if (cached) return cached;
  if (!isConfigured || !projectId) {
    throw new Error(
      "Sanity client requested but NEXT_PUBLIC_SANITY_PROJECT_ID is not set. " +
        "Gate callers with `isConfigured` before invoking getClient().",
    );
  }
  cached = createClient({
    projectId,
    dataset,
    apiVersion,
    useCdn: readToken ? false : true,
    token: readToken,
    perspective: "published",
  });
  return cached;
}
