import { firebase } from 'api/_services'
import { NextApiRequest, NextApiResponse } from 'next'

export default async (req: NextApiRequest, res: NextApiResponse) => {
  // Disabling endpoint for now, because we're not using it.
  // It also could benefit from tighter auth, so not anyone can check statuses (and device user-agents) for other voters.
  // And its understanding of the malware-check docs data structure is outdated.
  const disabled = true
  if (disabled) return res.status(400).json({ disabled })

  const { auth, election_id } = req.query

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

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

  // Fetch malware checks for this auth token
  const checks = await electionDoc.collection('malware-checks').where('auth', '==', auth).get()

  const checkStatuses = checks.docs.map((doc) => {
    const data = doc.data()
    return {
      confirmed: data.confirmed,
      created_at: data.created_at?._seconds ? new Date(data.created_at._seconds * 1000).toISOString() : null,
      device_info: data.device_info?.device_type || 'Unknown',
      match: data.match,
      user_agent: data.device_info?.user_agent || 'Unknown',
    }
  })

  // Count confirmed checks
  const confirmedCount = checkStatuses.filter((c) => c.confirmed === true).length

  return res.status(200).json({
    checks: checkStatuses,
    verified_count: confirmedCount,
  })
}
