import { NextApiRequest, NextApiResponse } from 'next'

import { firebase } from '../_services'
import { malwareCheckErrorGenerator } from './download'

export default async (req: NextApiRequest, res: NextApiResponse) => {
  const { auth_token, election_id, otp } = 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 otp !== 'string') return res.status(400).json({ error: 'Missing otp' })

  const electionDoc = firebase.firestore().collection('elections').doc(election_id)
  const checkDoc = electionDoc.collection('malware-checks').doc(auth_token)

  const malwareCheckError = malwareCheckErrorGenerator('decrypt-success', election_id, auth_token, otp, res)
  const check = await checkDoc.get()
  if (!check.exists) return malwareCheckError('No malware check found')

  const data = check.data()
  if (!data || !data.checks || !Array.isArray(data.checks)) return malwareCheckError('Invalid check data')

  // Find matching check entry by OTP
  const checkEntry = data.checks.find((entry: { otp?: string }) => entry.otp === otp)
  if (!checkEntry) return malwareCheckError('Invalid OTP', 401)

  // Update the specific check entry
  const updatedChecks = data.checks.map((entry: { otp?: string }) => {
    return entry.otp === otp ? { ...entry, decrypted_at: new Date() } : entry
  })

  await checkDoc.update({ checks: updatedChecks })

  return res.status(200).json({ success: true })
}
