/**
 * Content access. With PUBLIC_SANITY_PROJECT_ID set, everything comes from Sanity
 * (published documents only). Without it, the site renders from content/seed.json,
 * which has the same document shapes — handy for local work and for the prototype.
 */
import { createClient, type SanityClient } from '@sanity/client';
import seed from '../../../content/seed.json';

const projectId = import.meta.env.PUBLIC_SANITY_PROJECT_ID as string | undefined;
const dataset = (import.meta.env.PUBLIC_SANITY_DATASET as string | undefined) ?? 'production';

export const usingSanity = Boolean(projectId);
export const sanityConfig = { projectId: projectId ?? '', dataset };

// The preview deployment builds with SANITY_PERSPECTIVE=drafts (+ a read token) so Shanina
// can see drafts before publishing; the live site only ever shows published content.
const perspective = import.meta.env.SANITY_PERSPECTIVE === 'drafts' ? 'drafts' : 'published';

const client: SanityClient | null = usingSanity
  ? createClient({
      projectId,
      dataset,
      apiVersion: '2026-10-01',
      useCdn: false,
      perspective,
      token: import.meta.env.SANITY_READ_TOKEN,
    })
  : null;

// Loose document types: the schema in /studio is the source of truth.
export type Doc = Record<string, any> & { _id: string; _type: string };
export type Block = Record<string, any>;

// Drafts (ids starting with "drafts.") exist only in the Studio, never on the site.
const docs = (seed as Doc[]).filter((d) => !d._id.startsWith('drafts.'));
const byType = (type: string) => docs.filter((d) => d._type === type);
const byId = (id: string) => docs.find((d) => d._id === id);
const slugOf = (d: Doc) => d.slug?.current as string;
const newestFirst = (a: Doc, b: Doc) => String(b.publishedAt ?? '').localeCompare(String(a.publishedAt ?? ''));

const cache = new Map<string, Promise<any>>();
function query<T>(groq: string, params: Record<string, unknown> = {}): Promise<T> {
  const key = groq + JSON.stringify(params);
  if (!cache.has(key)) cache.set(key, client!.fetch<T>(groq, params));
  return cache.get(key)!;
}

export async function getSettings(): Promise<Doc> {
  if (client) return query(`*[_id == "siteSettings"][0]`);
  return byId('siteSettings')!;
}

export async function getPage(slug: string): Promise<Doc | undefined> {
  if (client) return query(`*[_type == "page" && slug.current == $slug][0]`, { slug });
  return byType('page').find((p) => slugOf(p) === slug);
}

/** Pages served by the generic [slug] route (home and listing pages have their own). */
export async function getGenericPageSlugs(): Promise<string[]> {
  const special = ['home', 'articles', 'recipes'];
  const slugs: string[] = client
    ? await query(`*[_type == "page" && defined(slug.current)].slug.current`)
    : byType('page').map(slugOf);
  return slugs.filter((s) => !special.includes(s));
}

const articleCard = `_id, title, slug, excerpt, coverImage, publishedAt, tags, layout`;

export async function getArticles(): Promise<Doc[]> {
  if (client) return query(`*[_type == "article" && defined(slug.current)] | order(publishedAt desc){${articleCard}}`);
  return byType('article').sort(newestFirst);
}

export async function getArticle(slug: string): Promise<Doc | undefined> {
  if (client) return query(`*[_type == "article" && slug.current == $slug][0]`, { slug });
  return byType('article').find((a) => slugOf(a) === slug);
}

const recipeCard = `_id, title, slug, image, tags, publishedAt, "spices": spices[]->{_id, name, slug}`;

function expandSpices(recipe: Doc): Doc {
  return { ...recipe, spices: (recipe.spices ?? []).map((r: any) => byId(r._ref)).filter(Boolean) };
}

export async function getRecipes(): Promise<Doc[]> {
  if (client) return query(`*[_type == "recipe" && defined(slug.current)] | order(publishedAt desc){${recipeCard}}`);
  return byType('recipe').sort(newestFirst).map(expandSpices);
}

export async function getRecipe(slug: string): Promise<Doc | undefined> {
  if (client) {
    return query(`*[_type == "recipe" && slug.current == $slug][0]{..., "spices": spices[]->{_id, name, slug}}`, { slug });
  }
  const recipe = byType('recipe').find((r) => slugOf(r) === slug);
  return recipe && expandSpices(recipe);
}

export async function getSpices(): Promise<Doc[]> {
  if (client) return query(`*[_type == "spice" && defined(slug.current)] | order(name asc)`);
  return byType('spice').sort((a, b) => a.name.localeCompare(b.name, 'he'));
}

export async function getSpice(slug: string): Promise<(Doc & { recipes: Doc[] }) | undefined> {
  if (client) {
    return query(
      `*[_type == "spice" && slug.current == $slug][0]{..., "recipes": *[_type == "recipe" && references(^._id)] | order(publishedAt desc){${recipeCard}}}`,
      { slug },
    );
  }
  const spice = byType('spice').find((s) => slugOf(s) === slug);
  if (!spice) return undefined;
  const recipes = byType('recipe')
    .filter((r) => (r.spices ?? []).some((ref: any) => ref._ref === spice._id))
    .map(expandSpices);
  return { ...spice, recipes };
}

/** Products marked to show on the site, in gallery order. */
export async function getProducts(): Promise<Doc[]> {
  if (client) return query(`*[_type == "product" && available != false] | order(coalesce(order, 999) asc, title asc)`);
  return byType('product')
    .filter((p) => p.available !== false)
    .sort((a, b) => (a.order ?? 999) - (b.order ?? 999) || String(a.title).localeCompare(String(b.title), 'he'));
}

/** Events that have not ended yet, soonest first. */
export async function getUpcomingEvents(): Promise<Doc[]> {
  const now = new Date().toISOString();
  if (client) {
    return query(`*[_type == "event" && coalesce(end, start) >= $now] | order(start asc)`, { now });
  }
  return byType('event')
    .filter((e) => (e.end ?? e.start) >= now)
    .sort((a, b) => a.start.localeCompare(b.start));
}

export async function getLatest(kind: 'article' | 'recipe' | 'event', count: number): Promise<Doc[]> {
  const list = kind === 'article' ? await getArticles() : kind === 'recipe' ? await getRecipes() : await getUpcomingEvents();
  return list.slice(0, count);
}
