import { Person } from "@/models/People";
import { GraphQLError } from "graphql/error";

export const personResolvers = {
    Query: {
        persons: async () => {
            try {
                return await Person.find();
            } catch (err: any) {
                throw new GraphQLError(err.message);
            }
        },
        person: async (_: any, { id }: { id: string }) => {
            try {
                const person = await Person.findById(id);
                if (!person) throw new GraphQLError("Person not found");
                return person;
            } catch (err: any) {
                throw new GraphQLError(err.message);
            }
        },
    },

    Mutation: {
        createPerson: async (_: any, { input }: any) => {
            try {
                const person = await Person.create({
                    ...input,
                    birthDate: new Date(input.birthDate),
                });
                return person;
            } catch (err: any) {
                throw new GraphQLError(err.message);
            }
        },
    },
};
