import { Brackets, In } from 'typeorm'
import { Resolver, Query, FieldResolver, Root, Args, Arg, Ctx, Directive } from 'type-graphql'
import { Attachment } from '@things-factory/attachment-base'
import { Domain, getQueryBuilderFromListParams, getRepository, ListParam } from '@things-factory/shell'
import { User } from '@things-factory/auth-base'
import { ProcessTemplate } from './process-template'
import { ProcessTemplateList } from './process-template-type'

@Resolver(ProcessTemplate)
export class ProcessTemplateQuery {
  @Query(returns => ProcessTemplate!, { nullable: true, description: 'To fetch a ProcessTemplate' })
  @Directive('@privilege(category: "process-template", privilege: "query", domainOwnerGranted: true)')
  async processTemplate(@Arg('id') id: string, @Ctx() context: ResolverContext): Promise<ProcessTemplate> {
    const { domain, user } = context.state

    const qb = await getRepository(ProcessTemplate)
      .createQueryBuilder('ProcessTemplate')
      .where('id=:id', { id })
      .andWhere(
        new Brackets(qb => {
          qb.where({ visibility: 'public' })
            .orWhere({
              visibility: 'domain',
              domain: { id: In([domain.id, domain.parentId]) }
            })
            .orWhere({
              visibility: 'private',
              creator: { id: user.id }
            })
        })
      )

    return qb.getOne()

    // return await getRepository(ProcessTemplate).findOne({
    //   where: {
    //     domain: { id: In([domain.id, domain.parentId].filter(Boolean)) },
    //     id
    //   }
    // })
  }

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

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

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

    return { items, total }
  }

  @Query(returns => ProcessTemplateList, { description: 'To fetch multiple ProcessTemplates' })
  @Directive('@privilege(category: "process-template", privilege: "query", domainOwnerGranted: true)')
  async processTemplates(@Args() params: ListParam, @Ctx() context: ResolverContext): Promise<ProcessTemplateList> {
    const { domain, user } = context.state
    /* 
      리스트에 포함되는 보드템플릿들 
      - visibility가 public 인 경우
      - visibility가 domain이며 컨텍스트의 도메인과 같은 경우
      - visibility가 private 이며, creator가 나인 경우
    */

    const queryBuilder = getQueryBuilderFromListParams({
      params,
      repository: await getRepository(ProcessTemplate),
      searchables: ['name', 'description']
    }).andWhere(
      new Brackets(qb => {
        qb.where({ visibility: 'public' })
          .orWhere({
            visibility: 'domain',
            domain: { id: In([domain.id, domain.parentId]) }
          })
          .orWhere({
            visibility: 'private',
            creator: { id: user.id }
          })
      })
    )

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

    return { items, total }
  }

  @FieldResolver(type => Boolean)
  async mine(@Root() processTemplate: ProcessTemplate, @Ctx() context: ResolverContext): Promise<boolean> {
    const { creatorId } = processTemplate
    const { user } = context.state

    return creatorId == user.id
  }

  @FieldResolver(type => Domain)
  async domain(@Root() processTemplate: ProcessTemplate): Promise<Domain> {
    return processTemplate.domainId && (await getRepository(Domain).findOneBy({ id: processTemplate.domainId }))
  }

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

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