import { createAdminClient } from '@/lib/supabase/admin'
import { AppShell } from '@/components/app/app-shell'
import { DEFAULT_TEMPLATES } from '@/lib/email-templates'
import { resolveTemplateMeta } from '@/lib/domain/email-policy'
import { EmailTemplatesAdmin, type TemplateRow, type VersionRow } from './templates-admin'
import { requireSurface } from '@/lib/auth/surface-guard'
import { ModeratorAccessCard } from '@/components/app/moderator-access-card'

/**
 * Admin · Email Templates (order-intake doc §11-16). Internal tool: view and
 * edit every system email template with preview, sample data, and version
 * history. Templates ship as code defaults; DB rows (migration 0008)
 * override them. Sending activates with the email backend.
 */
/** Stream / category / required for the editor: saved columns (migration 0028) win, else the shipped map. */
function metaFields(key: string, o: { email_stream?: string | null; category_key?: string | null; required?: boolean | null } | undefined) {
  const m = resolveTemplateMeta(key, o)
  return { email_stream: m.stream, category_key: m.category, required: m.required }
}

export default async function EmailTemplatesPage() {
  const { profile, canManage } = await requireSurface('email_templates')

  const admin = createAdminClient()
  // Tolerates a missing table until migration 0008 is applied.
  const { data: dbTemplates } = await admin.from('email_templates').select('*')
  const { data: dbVersions } = await admin
    .from('email_template_versions')
    .select('*')
    .order('created_at', { ascending: false })
    .limit(100)

  const overrides = new Map((dbTemplates ?? []).map((t) => [t.key, t]))
  const templates: TemplateRow[] = DEFAULT_TEMPLATES.map((d) => {
    const o = overrides.get(d.key)
    return {
      key: d.key,
      name: o?.name ?? d.name,
      subject: o?.subject ?? d.subject,
      body: o?.body ?? d.body,
      recipients_note: o?.recipients_note ?? d.recipients_note,
      cc_rules: o?.cc_rules ?? d.cc_rules,
      trigger_note: o?.trigger_note ?? d.trigger_note,
      internal_notes: o?.internal_notes ?? '',
      cta_text: o?.cta_text ?? '',
      footer: o?.footer ?? '',
      support_contact: o?.support_contact ?? '',
      version: o?.version ?? 0,
      active: o?.active ?? true,
      updated_by: o?.updated_by ?? null,
      updated_at: o?.updated_at ?? null,
      template_id: o?.id ?? null,
      is_custom: false,
      ...metaFields(d.key, o),
    }
  })
  // Duplicated / custom templates live only in the DB (2026-09-19, §33 "Duplicate template").
  const known = new Set(DEFAULT_TEMPLATES.map((d) => d.key))
  for (const o of dbTemplates ?? []) {
    if (known.has(o.key) || o.category === 'pilot_invitation') continue
    templates.push({
      key: o.key, name: o.name, subject: o.subject, body: o.body, recipients_note: o.recipients_note ?? '', cc_rules: o.cc_rules ?? '',
      trigger_note: o.trigger_note ?? '', internal_notes: o.internal_notes ?? '', cta_text: o.cta_text ?? '', footer: o.footer ?? '',
      support_contact: o.support_contact ?? '', version: o.version ?? 1, active: o.active ?? true, updated_by: o.updated_by ?? null,
      updated_at: o.updated_at ?? null, template_id: o.id, is_custom: true, ...metaFields(o.key, o),
    })
  }
  const versions: VersionRow[] = (dbVersions ?? []) as VersionRow[]

  return (
    <AppShell profile={profile}>
      <EmailTemplatesAdmin templates={templates} versions={versions} />
      <div className="mx-auto max-w-7xl px-4 pb-8">
        <ModeratorAccessCard surface="email_templates" canManage={canManage} />
      </div>
    </AppShell>
  )
}
