import { Resolver, Query, Args, ID, Info, Mutation } from '@nestjs/graphql';
import { Types } from 'mongoose';
import { Person } from '@/models/person.model';
import { PeopleService } from '@/people/people.service';
import { CreatePersonInput } from './dto/create-person.input';
import { UpdatePersonInput } from './dto/update-person.input';
import { ListArguments } from '@/dto/list.input';
import { ListPeopleResponse } from './dto/list-people.response';
import type { GraphQLResolveInfo } from 'graphql';
import graphqlFields from 'graphql-fields';

@Resolver()
export class PeopleResolver {

    constructor(private readonly peopleService: PeopleService) { }

    @Query(() => ListPeopleResponse, { name: "people" })
    async getPeople(@Info() info: GraphQLResolveInfo, @Args('input') input: ListArguments): Promise<ListPeopleResponse> {
        const fields = graphqlFields(info); const projection = this.peopleService.buildProjection(fields?.data); const { skip, limit, sort, filters } = input;
        return await this.peopleService.findAll(projection, skip, limit, sort, filters);
    }

    @Query(() => Person, { name: 'person', nullable: true })
    async getPerson(@Args('id', { type: () => ID }) id: string, @Info() info: GraphQLResolveInfo): Promise<Person | null> {
        const fields = graphqlFields(info); const projection = this.peopleService.buildProjection(fields); return this.peopleService.findById(new Types.ObjectId(id), projection);
    }

    @Mutation(() => Person, { name: 'createPerson' })
    async createPerson(@Args('input') input: CreatePersonInput): Promise<Person> { return this.peopleService.create(input) }

    @Mutation(() => Person, { name: 'updatePerson' })
    async updatePerson(@Args('uuid') uuid: string, @Args('input') input: UpdatePersonInput): Promise<Person> { return this.peopleService.update(uuid, input) }

    @Mutation(() => Boolean, { name: 'deletePerson' })
    async deletePerson(@Args('uuid') uuid: string): Promise<boolean> { return this.peopleService.delete(uuid) }

}
