import { Resolver, Query, FieldResolver, Root, Args, Arg, Ctx } 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 { NotificationRule } from './notification-rule'
import { NotificationRuleList } from './notification-rule-type'

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

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

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

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

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

    return { items, total }
  }

  @FieldResolver(type => String)
  async thumbnail(@Root() notificationRule: NotificationRule): Promise<string | undefined> {
    const attachment: Attachment = await getRepository(Attachment).findOne({
      where: {
        domain: { id: notificationRule.domainId },
        refType: NotificationRule.name,
        refBy: notificationRule.id
      }
    })

    return attachment?.fullpath
  }

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

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

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