// Typed PayloadCMS client. Same pattern as played/plaza — PayloadSDK with the
// Config from `@unom/cms/payload-types` for autocomplete + return-type safety.

import { PayloadSDK } from "@payloadcms/sdk";
import type { Config, Page, Post } from "@unom/cms/payload-types";
import { getLocale, type Locale } from "@/paraglide/runtime";

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

export const cmsClient = new PayloadSDK<Config>({
	baseURL: `${CMS_URL}/api`,
});

// The CMS only stores content for the locales declared in its localization
// config; getLocale() on the website can return any locale paraglide knows
// about. Narrow to the set the CMS supports.
function cmsLocale(locale?: Locale): "de" | "en" {
	const l = locale ?? getLocale();
	return l === "en" ? "en" : "de";
}

export async function findPageBySlug(
	slug: string,
	locale?: Locale,
): Promise<Page | null> {
	const res = await cmsClient.find({
		collection: "pages",
		where: { slug: { equals: slug } },
		limit: 1,
		locale: cmsLocale(locale),
		depth: 1,
	});
	return res.docs[0] ?? null;
}

export async function findPosts(locale?: Locale, limit = 50) {
	return cmsClient.find({
		collection: "posts",
		limit,
		sort: "-createdAt",
		locale: cmsLocale(locale),
	});
}

export async function findPostBySlug(
	slug: string,
	locale?: Locale,
): Promise<Post | null> {
	const res = await cmsClient.find({
		collection: "posts",
		where: { slug: { equals: slug } },
		limit: 1,
		locale: cmsLocale(locale),
		depth: 1,
	});
	return res.docs[0] ?? null;
}

export async function findFooter(locale?: Locale) {
	return cmsClient.findGlobal({ slug: "footer", locale: cmsLocale(locale) });
}

export async function findHeader(locale?: Locale) {
	return cmsClient.findGlobal({ slug: "header", locale: cmsLocale(locale) });
}

export type { Page, Post, Footer, Header } from "@unom/cms/payload-types";

// Lexical content shape lives inside Payload's serialized editor state.
// Pull a few aliases out for the renderer + block typing.
type PageBlocks = NonNullable<Page["blocks"]>;
export type RichTextBlock = Extract<PageBlocks[number], { blockType: "RichText" }>;
export type LexRoot = RichTextBlock["body"];
export type LexNode = LexRoot["root"]["children"][number];

type FooterSections = NonNullable<import("@unom/cms/payload-types").Footer["sections"]>;
export type NavigationSection = FooterSections[number];
export type NavigationLink = NonNullable<NavigationSection["entries"]>[number];
