// 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";

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

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

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

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

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

export async function findFooter(locale: "de" | "en" = "de") {
	return cmsClient.findGlobal({ slug: "footer", locale });
}

export async function findHeader(locale: "de" | "en" = "de") {
	return cmsClient.findGlobal({ slug: "header", 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];
