import { requestRecovery } from '@/lib/recover'
import { verifyTurnstile } from '@/lib/turnstile'

export async function POST(request: Request) {
  let type = ''
  let value = ''
  let turnstileToken = ''
  try {
    const body = await request.json()
    type = String(body.type ?? '')
    // `value` es el nombre de usuario (password) o el correo (resto). Se acepta
    // `email` por compatibilidad.
    value = String(body.value ?? body.email ?? '')
    turnstileToken = String(body.turnstileToken ?? '')
  } catch {
    return Response.json({ success: false, error: 'invalidRequest' }, { status: 400 })
  }
  const ip = (request.headers.get('x-forwarded-for') || '').split(',')[0].trim()
  if (!(await verifyTurnstile(turnstileToken, ip))) {
    return Response.json({ success: false, error: 'captchaFailed' })
  }
  const result = await requestRecovery(type, value)
  return Response.json(result)
}
