// src/lib/emdash.ts — server-side CMS fetch helpers (do not import on client) const EMDASH_URL = process.env.EMDASH_URL || 'http://localhost:4321' const EMDASH_TOKEN = process.env.EMDASH_API_TOKEN || '' export interface CmsItem { id: string slug: string status: string data: Record publishedAt: string | null } // emDash stores image fields as { provider, id, src } — flatten to plain URL strings. function normalizeData(data: Record): Record { const out: Record = {} for (const [k, v] of Object.entries(data)) { out[k] = v && typeof v === 'object' && 'src' in v ? (v as { src: unknown }).src ?? v : v } return out } async function fetchCollection(collection: string, limit = 20): Promise { if (!EMDASH_TOKEN) return [] try { const url = new URL(`/_emdash/api/content/${collection}`, EMDASH_URL) url.searchParams.set('status', 'published') url.searchParams.set('limit', String(limit)) const res = await fetch(url.toString(), { headers: { Authorization: `Bearer ${EMDASH_TOKEN}` }, next: { revalidate: 60 }, }) if (!res.ok) return [] const json = await res.json() as { data?: { items?: CmsItem[] }; items?: CmsItem[] } const items = json.data?.items ?? json.items ?? [] return items.map((item) => ({ ...item, data: normalizeData(item.data ?? {}) })) } catch { return [] } } export const getCampaigns = () => fetchCollection('campaigns') export const getSpecials = () => fetchCollection('specials') export const getBusinessHours = () => fetchCollection('business_hours', 1) export const getPromotions = () => fetchCollection('promotions') export const getFeaturedProductIds = async (): Promise => { const items = await fetchCollection('featured_products', 10) return items.flatMap(i => { const ids = i.data.product_ids return Array.isArray(ids) ? ids as string[] : [] }) } export const getBlogPosts = (limit = 10) => fetchCollection('posts', limit)