import { Args, Context, Int, Query, Resolver } from '@nestjs/graphql';
import { Person } from '../models/Person';
import { PersonService } from '../person.service';
import { Client } from '../../client';
import { HttpException } from '@nestjs/common';
import { UUID } from '../../global/scalars/UUID';

@Resolver(() => Person)
export class PersonResolverQ {
  constructor(
    private readonly service: PersonService,
  ) {}

  @Query(() => Person, { nullable: true })
  async Person(
    @Context('client') client: Client,
    @Args('id') id: UUID,
  ): Promise<Person> {
    if (!client.isMaster() && !client.isSelf(id)) return null;

    return await this.service.findOneById(id) as Person;
  }

  @Query(() => [Person], { nullable: true })
  async PersonFind(
    @Context('client') client: Client,
    @Args('givenName', { nullable: true }) givenName?: string,
    @Args('familyName', { nullable: true }) familyName?: string,
    @Args('email', { nullable: true }) email?: string,
    @Args('limit', { type: () => Int, nullable: true }) limit?: number,
    @Args('offset', { type: () => Int, nullable: true }) offset?: number,
  ): Promise<Person[]> {
    if (!client.isMaster()) return null;

    const filter: any = {}

    if (givenName) filter.givenName = givenName;
    if (familyName) filter.familyName = familyName;
    if (email) filter.email = email;

    let tmp = await this.service.find(filter, limit, offset);
    if (tmp.length > 1000) throw new HttpException('too many results', 413);

    return tmp
  }
}
