import { db } from '../utils/firebase'

export default defineEventHandler(async event => {
  const { relatiecode, email } = await readBody(event); 

  if (!relatiecode) throw createError({ statusCode: 400, statusMessage: 'no-relatiecode'})  
  if (!email) throw createError({ statusCode: 400, statusMessage: 'no-email'})

  try {
    const docRef = db.collection('ledenlijst').doc(relatiecode);
    const doc = await docRef.get();

    if (!doc.exists) throw createError({ statusCode: 400, statusMessage: 'incorrect'}) 

    const data = doc.data()

    if (data.email[0] === email || data.email[1] === email) {
      return { code: 'correct' }
    } else {
      throw createError({ statusCode: 400, statusMessage: 'incorrect'})
    }

  } catch (e) {
    throw createError({ statusCode: 500, statusMessage: e.message })
  }
})
