import { Arg, Args, Ctx, FieldResolver, Query, Resolver, Root } from 'type-graphql'

import { User } from '@things-factory/auth-base'
import { Domain, getQueryBuilderFromListParams, getRepository, ListParam } from '@things-factory/shell'

import { Process } from '../process/process'
import { ProcessGroup } from './process-group'
import { ProcessGroupList } from './process-group-type'

@Resolver(ProcessGroup)
export class ProcessGroupQuery {
  @Query(returns => ProcessGroup, { nullable: true, description: 'To fetch a ProcessGroup' })
  async processGroup(@Arg('id') id: string, @Ctx() context: ResolverContext): Promise<ProcessGroup> {
    const { domain } = context.state

    return await getRepository(ProcessGroup).findOne({
      where: { domain: { id: domain.id }, id }
    })
  }

  @Query(returns => ProcessGroupList, { description: 'To fetch multiple ProcessGroups' })
  async processGroups(@Args() params: ListParam, @Ctx() context: ResolverContext): Promise<ProcessGroupList> {
    const { domain } = context.state

    const queryBuilder = getQueryBuilderFromListParams({
      repository: getRepository(ProcessGroup),
      params,
      domain,
      searchables: ['name', 'description']
    })

    const [items, total] = await queryBuilder.getManyAndCount()

    return { items, total }
  }

  @FieldResolver(type => [Process])
  async processes(@Root() group: ProcessGroup) {
    return await getRepository(Process).findBy({
      group: { id: group.id }
    })
  }

  @FieldResolver(type => Domain)
  async domain(@Root() group: ProcessGroup) {
    return await getRepository(Domain).findOneBy({ id: group.domainId })
  }

  @FieldResolver(type => User)
  async updater(@Root() group: ProcessGroup): Promise<User> {
    return await getRepository(User).findOneBy({ id: group.updaterId })
  }

  @FieldResolver(type => User)
  async creator(@Root() group: ProcessGroup): Promise<User> {
    return await getRepository(User).findOneBy({ id: group.creatorId })
  }
}
