import { registerAccount } from '@/lib/register'
import { verifyTurnstile } from '@/lib/turnstile'

export async function POST(request: Request) {
  let body: Record<string, string>
  try {
    body = await request.json()
  } catch {
    return Response.json({ success: false, error: 'invalidRequest' }, { status: 400 })
  }

  const ip = (request.headers.get('x-forwarded-for') || '').split(',')[0].trim()
  if (!(await verifyTurnstile(body.turnstileToken ?? '', ip))) {
    return Response.json({ success: false, error: 'captchaFailed' })
  }

  const result = await registerAccount({
    password: body.password ?? '',
    confPassword: body.confPassword ?? '',
    email: body.email ?? '',
    confEmail: body.confEmail ?? '',
    recruiter: body.recruiter ?? '',
  })
  return Response.json(result)
}
