import { cookies } from 'next/headers'
import { NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'
import { createGoogleOAuthClient, googleAuthConfigured, googleContextCookie, safeNextPath, type GoogleContext } from '@/lib/auth/google-oauth'
import { recaptchaHostname, verifyRecaptcha } from '@/lib/security/recaptcha'
import { clientIp, rateLimit } from '@/lib/security/rate-limit'
import { publicOrigin } from '@/lib/app-url'

const inputSchema = z.object({
  mode: z.enum(['login', 'signup']),
  role: z.enum(['broker', 'dispatcher', 'driver']).optional(),
  company: z.string().trim().max(120).optional(),
  next: z.string().max(1000).optional(),
  captchaToken: z.string().max(4096).nullable(),
})

export async function POST(req: NextRequest) {
  if (!googleAuthConfigured()) return NextResponse.json({ error: 'Google sign-in is not configured yet.' }, { status: 503 })
  const parsed = inputSchema.safeParse(await req.json().catch(() => ({})))
  if (!parsed.success) return NextResponse.json({ error: 'Check the details and try again.' }, { status: 400 })
  const input = parsed.data
  const gate = rateLimit(`google-oauth:${clientIp(req.headers)}`, 10, 15 * 60_000)
  if (!gate.allowed) return NextResponse.json({ error: 'Too many sign-in attempts. Try again in a few minutes.' }, { status: 429 })
  const verified = await verifyRecaptcha(input.captchaToken, input.mode === 'signup' ? 'google_signup' : 'google_login', recaptchaHostname(req.headers.get('host')))
  if (!verified.ok) return NextResponse.json({ error: verified.error }, { status: 403 })

  const context: GoogleContext = {
    mode: input.mode,
    role: input.mode === 'signup' ? input.role ?? 'broker' : 'broker',
    company: input.mode === 'signup' ? input.company ?? '' : '',
    next: safeNextPath(input.next),
  }
  const supabase = await createGoogleOAuthClient()
  const { data, error } = await supabase.auth.signInWithOAuth({
    provider: 'google',
    options: { redirectTo: `${publicOrigin(req)}/api/auth/google/callback`, skipBrowserRedirect: true },
  })
  const contextCookie = googleContextCookie(data.flowId ?? '')
  if (error || !data.url || !contextCookie) {
    return NextResponse.json({ error: 'Could not start Google sign-in. Please try again.' }, { status: 502 })
  }
  const jar = await cookies()
  jar.set(contextCookie, JSON.stringify(context), { httpOnly: true, secure: process.env.NODE_ENV === 'production', sameSite: 'lax', path: '/', maxAge: 600 })
  return NextResponse.json({ url: data.url })
}
