import 'server-only'
// tdd-guard:skip — Supabase I/O glue; the pure parsing (parseStoredTemplateItems)
// is unit-tested in templates.test.ts. Verified via integration once applied.

import type { SupabaseClient } from '@supabase/supabase-js'
import { parseStoredTemplateItems, type ResolvedTemplateItem } from './templates'
import type { AgendaType } from './types'

/** Custom Stammdaten template items for a type, or null if none / not provisioned. */
export async function loadAgendaTemplate(
  supabase: SupabaseClient,
  type: AgendaType,
): Promise<ResolvedTemplateItem[] | null> {
  const { data, error } = await supabase
    .from('agenda_template')
    .select('items')
    .eq('agenda_type', type)
    .maybeSingle()
  if (error || !data) return null
  const items = parseStoredTemplateItems((data as { items?: unknown }).items)
  return items.length > 0 ? items : null
}

/** All custom templates as a map type → items (empty when none / not provisioned). */
export async function loadAllAgendaTemplates(
  supabase: SupabaseClient,
): Promise<Record<string, ResolvedTemplateItem[]>> {
  const { data, error } = await supabase.from('agenda_template').select('agenda_type, items')
  if (error || !data) return {}
  const out: Record<string, ResolvedTemplateItem[]> = {}
  for (const row of data as Array<{ agenda_type: string; items: unknown }>) {
    out[row.agenda_type] = parseStoredTemplateItems(row.items)
  }
  return out
}
