import { Resolver, Subscription, Root, Arg } from 'type-graphql'
import { filter, pipe } from 'graphql-yoga'
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 pipe(
        pubsub.subscribe('process'),
        filter((payload: { process: Process }) => {
          const { id: processId, domainId } = payload.process

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

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

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