import { Resolver, Subscription, Root, Arg } from 'type-graphql'
import { filter, pipe } from 'graphql-yoga'
import { pubsub } from '@things-factory/shell'
import { ProcessGroup } from './process-group'

@Resolver(ProcessGroup)
export class ProcessGroupSubscription {
  @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-group'),
        filter((payload: { processGroup: ProcessGroup }) => {
          const { id: processGroupId, domainId } = payload.processGroup

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

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

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