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

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

  if (!email) throw createError({ statusCode: 400, statusMessage: 'no-email'})
  if (!token) throw createError({ statusCode: 400, statusMessage: 'no-token'})
  
  try {
    await auth.verifyIdToken(token)
  } catch (e) {
    console.log(e);
    throw createError({ statusCode: 500, statusMessage: 'error-verify-id'})
  }

  try {
    const ledenlijstRef = db.collection('ledenlijst')

    const snapshot = await ledenlijstRef.where("email", "array-contains", email).get()
    
    if (snapshot.empty) {
      throw createError({ statusCode: 400, statusMessage: 'no-relatiecode'})
    }

    let relatiecodes = [];
    let persons = [];

    snapshot.forEach(doc => {
      relatiecodes.push(doc.id)
      const data = doc.data()
      persons.push({ fullName: data.fullName, relatiecode: doc.id })
    });
    
    return { code: 'success', relatiecodes: relatiecodes, persons: persons }

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