import { filter, pipe } from 'graphql-yoga'
import { Arg, Resolver, FieldResolver, Root, Subscription } from 'type-graphql'

import { pubsub, ScalarDate } from '@things-factory/shell'

import { Notification } from './notification'

@Resolver(Notification)
export class NotificationSubscription {
  @Subscription({
    subscribe: ({ args, context, info }) => {
      const { subjects = [] } = args

      return pipe(
        pubsub.subscribe('notification'),
        filter(async (payload: { notification: Notification }) => {
          /* normally, subscription context doesn't have domain */
          const { domain, user } = context.state

          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 }) subjects: string[]): Notification {
    return payload.notification
  }
}
