import { getSession } from '@/lib/session'
import { requestEmailChange } from '@/lib/change-email'

export async function POST(request: Request) {
  const session = await getSession()
  if (!session.accountId) return Response.json({ success: false, error: 'notAuthenticated' }, { status: 401 })
  let b: Record<string, string> = {}
  try {
    b = await request.json()
  } catch {
    return Response.json({ success: false, error: 'invalidRequest' }, { status: 400 })
  }
  return Response.json(
    await requestEmailChange(
      session,
      String(b.currentPassword ?? ''),
      String(b.currentEmail ?? ''),
      String(b.newEmail ?? ''),
      String(b.confEmail ?? ''),
      String(b.token ?? ''),
    ),
  )
}
