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

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

  if (!token) throw createError({ statusCode: 400, statusMessage: 'no-token'})
  if (!body) throw createError({ statusCode: 400, statusMessage: 'no-body'})
  if (!title) throw createError({ statusCode: 400, statusMessage: 'no-title'})
  if (!topic) throw createError({ statusCode: 400, statusMessage: 'no-topic'})

 
  let decodedToken = null;

  try {
    decodedToken = await auth.verifyIdToken(token)
  } catch (e) {
    console.log(e)
    throw createError({ statusCode: 500, statusMessage: 'error-verify-id'})
  }

  if (!decodedToken) throw createError({ statusCode: 500, statusMessage: 'error-verify-id-test'})

  try {
    const uid = decodedToken.uid;
    
    const docRef = db.collection('users').doc(uid);
    const doc = await docRef.get();

    if (!doc.exists) throw createError({ statusCode: 500, statusMessage: 'doc-not-found'})

    const data = doc.data()

    if (!data.sendNews) throw createError({ statusCode: 500, statusMessage: 'no-permissions'})

    const message = {
      notification: {
        title: title,
        body: body,
      },         
      webpush: {
        notification: {
          icon: '/ios/256.png',
        }
      },
      topic: topic,
      apns: {
        payload: {
          aps: {
            sound: 'default'
          }
        }
      }
    };
    const response = await messaging.send(message)

    console.log('Successfully sent message:', response);

    return { code: 'success', response: response }

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