import { NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'
import { getSessionUser } from '@/lib/auth'
import { createAdminClient } from '@/lib/supabase/admin'

/**
 * Save an email template edit (admin only). Every save also writes a version
 * row so a bad edit can be restored ("if an email template is edited
 * incorrectly, it can confuse carriers, brokers, and Synchron"). Sending is
 * the email backend — this stores content only.
 */

const schema = z.object({
  key: z.string().trim().min(1).max(80),
  name: z.string().trim().min(1).max(160),
  subject: z.string().trim().min(1).max(300),
  body: z.string().trim().min(1).max(20_000),
  recipients_note: z.string().trim().max(500).optional().or(z.literal('')),
  cc_rules: z.string().trim().max(500).optional().or(z.literal('')),
  trigger_note: z.string().trim().max(500).optional().or(z.literal('')),
  internal_notes: z.string().trim().max(2000).optional().or(z.literal('')),
  active: z.boolean(),
  reason: z.string().trim().max(300).optional().or(z.literal('')),
})

export async function POST(req: NextRequest) {
  const user = await getSessionUser()
  if (!user || user.role !== 'admin') {
    return NextResponse.json({ error: 'Admin only.' }, { status: 403 })
  }

  const parsed = schema.safeParse(await req.json().catch(() => ({})))
  if (!parsed.success) {
    return NextResponse.json({ error: 'Invalid template.' }, { status: 400 })
  }
  const input = parsed.data

  const admin = createAdminClient()
  const { data: tpl, error } = await admin
    .from('email_templates')
    .upsert(
      {
        key: input.key,
        name: input.name,
        subject: input.subject,
        body: input.body,
        recipients_note: input.recipients_note || null,
        cc_rules: input.cc_rules || null,
        trigger_note: input.trigger_note || null,
        internal_notes: input.internal_notes || null,
        active: input.active,
        updated_by: user.name || user.email,
        updated_at: new Date().toISOString(),
      },
      { onConflict: 'key' },
    )
    .select()
    .single()
  if (error || !tpl) {
    return NextResponse.json(
      { error: 'Could not save — is migration 0008 applied?' },
      { status: 500 },
    )
  }

  // Version history: every save is restorable.
  await admin.from('email_template_versions').insert({
    template_id: tpl.id,
    subject: input.subject,
    body: input.body,
    edited_by: user.name || user.email,
    reason: input.reason || null,
  })

  return NextResponse.json({ ok: true, template: tpl })
}
