import { pubsub } from '@things-factory/shell'
import { logger } from '@things-factory/env'

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

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

function notifier(context) {
  return async function ({
    receivers,
    privileges,
    tokens,
    topic,
    type,
    subject = 'info',
    title,
    body,
    image,
    url,
    actions,
    timestamp = Date.now(),
    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: {
            type,
            url,
            timestamp: String(timestamp)
          },
          image,
          actions
        })
      } else {
        /* for send publish notification to clients */
        // TODO CONFIRM data format
        await pubsub.publish('notification', {
          notification: {
            domain,
            subject,
            type,
            title,
            body,
            image,
            url,
            timestamp
          }
        })
      }
    } catch (err) {
      logger.error(err)
    }
  }
}

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

  await next()
}
