import { NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'
import { claimProfile } from '@/lib/data/pilot-network'

/**
 * Public (no login): the Claim My Pilot Profile form (§20–§22). The token
 * from the emailed link is the only credential; it is erased on success
 * (answer 6).
 */
const schema = z.object({
  token: z.string().regex(/^[a-f0-9]{48}$/),
  account_type: z.enum(['pilot_driver', 'pilot_company']),
  name: z.string().trim().min(1).max(160),
  company_name: z.string().trim().max(160).nullable(),
  email: z.string().trim().email().max(200),
  phone: z.string().trim().max(40).nullable(),
  states: z.array(z.string().trim().length(2)).min(1).max(60),
  capability_keys: z.array(z.string().trim().max(80)).max(100),
  opt_in: z.boolean(),
})

export async function POST(req: NextRequest) {
  const parsed = schema.safeParse(await req.json().catch(() => ({})))
  if (!parsed.success) return NextResponse.json({ error: parsed.error.issues[0]?.message ?? 'Please check the form.' }, { status: 400 })
  const { token, ...input } = parsed.data
  const out = await claimProfile(token, input)
  if (!out.ok) return NextResponse.json({ error: out.error }, { status: 409 })
  return NextResponse.json({ ok: true, account_type: out.profile.account_type, name: out.profile.name, email: out.profile.email, phone: out.profile.phone, company_name: out.profile.company_name })
}
