// Thin REST client for the unom CMS. Pages have `read: () => true` access,
// globals likewise — so no auth is needed for fetching content. Route loaders
// in TanStack Start call these on the server during SSR and on the client
// during navigation.

const CMS_URL = "https://cms.unom.io";

type LexNode = {
	type: string;
	children?: LexNode[];
	tag?: string;
	text?: string;
	fields?: { url?: string; newTab?: boolean; linkType?: string };
	listType?: string;
};

type LexRoot = { root: LexNode };

type RichTextBlock = { blockType: "RichText"; body: LexRoot; id?: string };

type Page = {
	id: number;
	slug: string;
	title: string;
	description?: string | null;
	blocks?: Array<RichTextBlock | { blockType: string; [k: string]: unknown }>;
	meta?: { title?: string | null; description?: string | null };
};

type NavigationLink = {
	blockType: "NavigationLink";
	label: string;
	to: string;
	id?: string;
};

type NavigationSection = {
	blockType: "NavigationSection";
	title?: string | null;
	entries?: NavigationLink[] | null;
	id?: string;
};

type Footer = {
	id: number;
	tagline?: string | null;
	sections?: NavigationSection[];
};

type Header = {
	id: number;
	sections?: NavigationSection[];
};

async function cmsFetch<T>(path: string): Promise<T> {
	const res = await fetch(`${CMS_URL}${path}`, {
		headers: { Accept: "application/json" },
	});
	if (!res.ok) {
		throw new Error(`CMS ${path} → ${res.status}`);
	}
	return res.json() as Promise<T>;
}

export async function findPageBySlug(
	slug: string,
	locale = "de",
): Promise<Page | null> {
	const qs = new URLSearchParams({
		"where[slug][equals]": slug,
		limit: "1",
		locale,
		depth: "1",
	});
	const data = await cmsFetch<{ docs: Page[] }>(`/api/pages?${qs}`);
	return data.docs?.[0] ?? null;
}

export async function findFooter(locale = "de"): Promise<Footer> {
	return cmsFetch<Footer>(`/api/globals/footer?locale=${locale}&depth=1`);
}

export async function findHeader(locale = "de"): Promise<Header> {
	return cmsFetch<Header>(`/api/globals/header?locale=${locale}&depth=1`);
}

export type { Page, RichTextBlock, LexRoot, LexNode, Footer, Header, NavigationSection, NavigationLink };
