import { NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'
import { getSessionUser } from '@/lib/auth'
import { canAccessSurface } from '@/lib/domain/moderator-access'
import { demoDimensionWarnings } from '@/lib/demo/dimension-alert'
import { workspaceDimensionAlertsEnabled } from '@/lib/domain/dimension-alerts'
import { normalizeEmail, recipientContext, sendPlatformEmail } from '@/lib/email/send'

const value = z.number().int().min(0).max(10_000_000).nullable()
const schema = z.object({
  to: z.email().max(200),
  permit: z.object({ length: value, width: value, height: value, weight: value }),
})

/** Send a marked test through the real template, policy and email provider. */
export async function POST(req: NextRequest) {
  if (process.env.NODE_ENV !== 'development') return NextResponse.json({ error: 'Not found.' }, { status: 404 })
  if (!workspaceDimensionAlertsEnabled()) return NextResponse.json({ error: 'Workspace dimension alerts are paused.' }, { status: 503 })
  const user = await getSessionUser()
  if (!user || !canAccessSurface(user, 'email_templates')) {
    return NextResponse.json({ error: 'Sign in with email-template admin access to send a test.' }, { status: 403 })
  }
  const parsed = schema.safeParse(await req.json().catch(() => ({})))
  if (!parsed.success) return NextResponse.json({ error: 'Enter a valid email and permit dimensions.' }, { status: 400 })

  const warnings = demoDimensionWarnings(parsed.data.permit)
  if (!warnings.length) return NextResponse.json({ error: 'The sample permit has no mismatch to alert on.' }, { status: 400 })

  const recipient = await recipientContext(parsed.data.to)
  if (normalizeEmail(recipient.sendTo) !== normalizeEmail(parsed.data.to)) {
    return NextResponse.json({ error: 'This account uses a different delivery address. Enter that address to send a test.' }, { status: 400 })
  }

  const result = await sendPlatformEmail({
    templateKey: 'permit_dimension_alert',
    to: parsed.data.to,
    actorUserId: user.id,
    subjectPrefix: '[DEMO TEST] ',
    appendText: 'DEMO TEST ONLY — This is a sample permit. No real trip or permit needs action.',
    data: {
      trip_id: 'DEMO-HH-123456789',
      permit_number: 'TEST-GA-48392',
      permit_state: 'GA',
      permit_source: 'Demo sample',
      mismatch_rows: warnings.map((warning) => `- ${warning.message}`).join('\n'),
      workspace_link: '',
    },
    tags: { kind: 'dimension_alert_demo', trip: 'demo', permit: 'demo' },
  })
  return NextResponse.json({ status: result.status, reason: result.reason ?? null, subject: result.subject }, { status: result.status === 'failed' ? 502 : 200 })
}
