import { Subscription, Root, Arg, Resolver } from 'type-graphql'
import { pubsub } from '@things-factory/shell'
import { withFilter } from 'graphql-subscriptions'
import { Notification } from './notification'

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

@Resolver()
export class NotificationResolver {
  @Subscription({
    subscribe: withFilter(
      () => pubsub.asyncIterator('notification'),
      (payload, variables, context, info) => {
        /* normally, subscription context doesn't have domain */
        const { domain, user } = context.state

        const { subjects = [] } = variables
        const {
          notification: { subject, domain: pdomain }
        } = payload

        const subdomain = pdomain?.subdomain

        if (subdomain) {
          if (domain?.subdomain) {
            if (subdomain !== domain.subdomain) {
              return false
            }
          } else if (!user.domains.find(d => d.subdomain === subdomain)) {
            return false
          }
        }

        return !subject || subjects.indexOf(subject) !== -1
      }
    )
  })
  notification(
    @Root() payload: { notification: Notification },
    @Arg('subjects', type => [String], { nullable: true }) subject: string[]
  ): Notification {
    return payload.notification
  }
}
