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

const schema = z.object({
  email: z.string().trim().toLowerCase().email().max(254),
  role: z.enum(['broker', 'carrier', 'dispatcher', 'driver', 'other']).optional(),
  // where the signup came from, e.g. 'landing' or 'signup · Company Name'
  source: z.string().trim().max(160).optional(),
  // honeypot — real users never fill this
  company_website: z.string().max(0).optional().or(z.literal('')),
})

/** Landing-page early-access signup. Public, no session required. */
export async function POST(req: NextRequest) {
  const parsed = schema.safeParse(await req.json().catch(() => ({})))
  if (!parsed.success) {
    return NextResponse.json({ error: 'Please enter a valid email address.' }, { status: 400 })
  }
  const { email, role, source } = parsed.data

  const admin = createAdminClient()
  const { error } = await admin.from('early_access_signups').insert({
    email,
    role: role ?? null,
    source: source || 'landing',
  })

  if (error) {
    // 23505 = unique violation: already signed up — that's a success for the visitor.
    if (error.code === '23505') {
      return NextResponse.json({ ok: true, message: "You're already on the list — we'll be in touch." })
    }
    console.error('early-access insert failed:', error.message)
    return NextResponse.json(
      { error: 'Could not save your signup right now — please try again later.' },
      { status: 500 },
    )
  }

  return NextResponse.json({ ok: true, message: "You're on the list — we'll reach out with your access." })
}
