import { NextApiRequest, NextApiResponse } from 'next'

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

export default async (req: NextApiRequest, res: NextApiResponse) => {
  const { auth_token, confirmed, election_id, issue_description, 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 confirmed !== 'boolean') return res.status(400).json({ error: 'Missing confirmed' })
  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 check = await checkDoc.get()
  const malwareCheckError = malwareCheckErrorGenerator('confirm', election_id, auth_token, otp, res)
  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 - add confirmation
  const updatedChecks = data.checks.map((entry: { confirmations?: unknown[]; otp?: string }) => {
    if (entry.otp === otp) {
      const confirmations = Array.isArray(entry.confirmations) ? [...entry.confirmations] : []
      confirmations.push({
        confirmed,
        confirmed_at: new Date(),
        issue_description: issue_description || null,
        otp,
      })
      return { ...entry, confirmations }
    }

    return entry
  })

  await checkDoc.update({ checks: updatedChecks })

  if (!confirmed)
    await pushover(
      'Malware check: Reported issue',
      `${election_id}: ${auth_token} (OTP: ${otp})\n${issue_description ? `Issue: ${issue_description}` : ''}`,
    )

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