import { firestore } from 'firebase-admin'
import { NextApiRequest, NextApiResponse } from 'next'

import { firebase } from '../_services'
import { generateEmailLoginCode } from '../admin-login'

export default async (req: NextApiRequest, res: NextApiResponse) => {
  const { auth_token, election_id, encrypted_randomizers } = req.body

  if (typeof election_id !== 'string') return res.status(400).json({ error: 'Missing election_id' })
  if (typeof auth_token !== 'string') return res.status(400).json({ error: 'Missing auth_token' })
  if (typeof encrypted_randomizers !== 'string') return res.status(400).json({ error: 'Missing encrypted_randomizers' })

  const electionDoc = firebase.firestore().collection('elections').doc(election_id)

  // Generate 6-digit OTP
  const otp = generateEmailLoginCode()

  // Create new check entry
  const checkEntry = { created_at: new Date(), encrypted_randomizers, otp }

  // Add new check entry to checks array
  await electionDoc
    .collection('malware-checks')
    .doc(auth_token)
    .set({ auth_token, checks: firestore.FieldValue.arrayUnion(checkEntry) }, { merge: true })

  return res.status(200).json({ otp })
}
