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 { ProcessGroup } from '../process-group/process-group'
import { Process } from './process'
import { ProcessList } from './process-type'

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

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

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

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

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

    return { items, total }
  }

  @Query(returns => ProcessList, { description: 'To fetch Processs created by me' })
  async processesCreatedByMe(@Args() params: ListParam, @Ctx() context: ResolverContext): Promise<ProcessList> {
    const { domain, user } = context.state

    const queryBuilder = getQueryBuilderFromListParams({
      repository: getRepository(Process),
      params,
      domain,
      alias: 'process',
      searchables: ['name', 'description']
    }).andWhere('process.creator = :user', { user: user.id })

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

    return { items, total }
  }

  @FieldResolver(type => ProcessGroup)
  async group(@Root() process: Process) {
    return (
      process.groupId &&
      (await getRepository(ProcessGroup).findOneBy({
        id: process.groupId
      }))
    )
  }

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

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

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