import { redirect } from 'next/navigation'
import { getProfile, getSessionUser } from '@/lib/auth'
import { createAdminClient } from '@/lib/supabase/admin'
import { AppShell } from '@/components/app/app-shell'
import { DEFAULT_TEMPLATES } from '@/lib/email-templates'
import { EmailTemplatesAdmin, type TemplateRow, type VersionRow } from './templates-admin'

/**
 * 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.
 */
export default async function EmailTemplatesPage() {
  const user = await getSessionUser()
  if (!user) redirect('/login')
  if (user.role !== 'admin') redirect('/dashboard')
  const profile = (await getProfile())!

  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 ?? '',
      active: o?.active ?? true,
      updated_by: o?.updated_by ?? null,
      updated_at: o?.updated_at ?? null,
      template_id: o?.id ?? null,
    }
  })
  const versions: VersionRow[] = (dbVersions ?? []) as VersionRow[]

  return (
    <AppShell profile={profile}>
      <EmailTemplatesAdmin templates={templates} versions={versions} />
    </AppShell>
  )
}
