import { getGameAccounts } from '@/lib/auth'
import { getSession } from '@/lib/session'
import { setGameAccountSession } from '@/lib/account-session'

export async function POST(request: Request) {
  const session = await getSession()
  if (!session.bnetId) {
    return Response.json({ success: false, error: 'notAuthenticated' }, { status: 401 })
  }
  let accountId: number
  try {
    const body = await request.json()
    accountId = Number(body.accountId)
  } catch {
    return Response.json({ success: false, error: 'invalidRequest' }, { status: 400 })
  }

  const games = await getGameAccounts(session.bnetId)
  const chosen = games.find((g) => g.id === accountId)
  if (!chosen) {
    return Response.json({ success: false, error: 'invalidAccount' })
  }
  setGameAccountSession(session, chosen)
  await session.save()
  return Response.json({ success: true })
}
