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

@Resolver(Process)
export class ProcessSubscription {
  @Subscription({
    subscribe: (_, args, context, info) => {
      const { domain, user } = context.state
      const { id } = args
      const subdomain = domain?.subdomain

      if (!domain) {
        throw new Error('domain required')
      }

      if (!user.domains?.find(d => d.subdomain === subdomain)) {
        throw new Error(`domain(${subdomain}) is not working for user(${user.email}).`)
      }

      return withFilter(
        () => pubsub.asyncIterator('process'),
        (payload, variables, context, info) => {
          const { domainId, id: processId } = payload.process

          if (domainId !== domain.id) {
            return false
          }

          if (id !== processId) {
            return false
          }

          return true
        }
      )(_, args, context, info)
    }
  })
  process(@Root() payload: { process: Process }, @Arg('id') id: string): Process {
    return payload.process
  }
}
