import { pubsub } from '@things-factory/shell'
import { database } from 'firebase-admin'

import { notify } from '../controllers/fcm'

const debug = require('debug')('things-factory:notification:notification-middleware')

function notifier(context) {
  return async function ({
    receivers,
    privileges,
    tokens,
    topic,
    subject = 'info',
    title,
    body,
    // data,
    image,
    url,
    actions,
    timestamp = new Date(),
    mode = 'background'
  }) {
    const { domain, user } = context.state

    try {
      if (mode === 'background') {
        /* for send webpush notification message */

        await notify({
          receivers,
          privileges,
          tokens,
          topic,
          title,
          body,
          data: {
            url,
            timestamp
          },
          image,
          actions
        })
      } else {
        /* for send publish notification to clients */
        // TODO CONFIRM data format
        await pubsub.publish('notification', {
          notification: {
            domain,
            subject,
            title,
            body,
            image,
            url,
            timestamp
          }
        })
      }
    } catch (err) {
      debug(err)
    }
  }
}

export async function notificationMiddleware(context: any, next: any) {
  if (!context.state.notify) {
    context.state.notify = notifier(context)
  }

  await next()
}
