import Router from 'koa-router'
import { ILike } from 'typeorm'

import { User } from '@things-factory/auth-base'
import { getRepository } from '@things-factory/shell'

import { getConfig, register, unregister } from '../controllers/fcm'

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

export const notificationRouter = new Router({
  prefix: '/notification'
})

notificationRouter.get('/config', async (context, next) => {
  const config = getConfig()

  context.type = 'application/json'
  context.body = config
})

notificationRouter.post('/register', async (context, next) => {
  const { user } = context.state
  const { body } = context.request
  context.body = await register(user, body)
  context.status = 200
})

notificationRouter.post('/unregister', async (context, next) => {
  const { user } = context.state
  const { body } = context.request
  context.body = await unregister(user, body)
  context.status = 200
})

notificationRouter.post('/notify', async (context, next) => {
  const { user, domain, notify } = context.state
  const repository = getRepository(User)

  var { receivers, ...options } = context.request.body

  debug('post:/notify', receivers, receivers.split(','), options)

  // TODO filter only users having current domain privilege
  receivers = (
    await Promise.all(
      receivers
        .split(',')
        .map(email => email.trim())
        .map(async email => {
          var receiver: User = await repository.findOneBy({ email: ILike(email) })
          return receiver && receiver.id
        })
    )
  ).filter(receiver => !!receiver)

  debug('post:/notify', receivers, user.id)

  await notify({
    receivers: receivers.length > 0 ? receivers : [user.id],
    ...options
  })

  context.body = {
    success: true
  }
})
