import { authenticate, getGameAccounts } from '@/lib/auth'
import { getSession } from '@/lib/session'
import { setGameAccountSession } from '@/lib/account-session'
import { verifyTurnstile } from '@/lib/turnstile'
import { EMAIL_RE } from '@/lib/bnet'

export async function POST(request: Request) {
  let email = ''
  let password = ''
  let turnstileToken = ''
  try {
    const body = await request.json()
    email = String(body.email ?? '').trim()
    password = String(body.password ?? '')
    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' })
  }

  if (!email || !password) {
    return Response.json({ success: false, error: 'missingFields' })
  }
  // Con Battle.net se entra con el CORREO, no con la cuenta de juego («15#1»).
  if (!EMAIL_RE.test(email)) {
    return Response.json({ success: false, error: 'notAnEmail' })
  }

  const account = await authenticate(email, password)
  if (!account) {
    return Response.json({ success: false, error: 'invalidCredentials' })
  }

  const session = await getSession()
  session.bnetId = account.id
  session.bnetEmail = account.email

  const games = await getGameAccounts(account.id)
  let needsSelection = true
  if (games.length === 1) {
    setGameAccountSession(session, games[0])
    needsSelection = false
  } else {
    // 0 o >1 cuentas de juego: dejar la selección pendiente
    delete session.username
    delete session.accountId
  }
  await session.save()

  return Response.json({ success: true, needsSelection })
}
