import { Resolver, Mutation, Args, Context } from '@nestjs/graphql';
import { UseGuards } from '@nestjs/common';
import { ChildType } from '../types/child.type';
import { CreateChildInput, UpdateChildInput } from '../inputs/child.input';
import { ChildrenService } from '../../modules/children/children.service';
import { GqlAuthGuard } from '../guards/gql-auth.guard';

@Resolver(() => ChildType)
@UseGuards(GqlAuthGuard)
export class ChildResolver {
  constructor(private readonly childrenService: ChildrenService) {}

  @Mutation(() => ChildType)
  async createChild(
    @Args('input') input: CreateChildInput,
    @Context() context: any,
  ): Promise<ChildType> {
    const userId = context.req?.user?.userId;

    if (!userId) {
      throw new Error('User not authenticated');
    }

    const child = await this.childrenService.create(userId, input.familyId, {
      name: input.name,
      birthDate: input.birthDate.toISOString(),
      gender: input.gender,
      photoUrl: input.photoUrl,
      medicalInfo: input.medicalInfo,
    });

    return child as any;
  }

  @Mutation(() => ChildType)
  async updateChild(
    @Args('id') id: string,
    @Args('input') input: UpdateChildInput,
    @Context() context: any,
  ): Promise<ChildType> {
    const userId = context.req?.user?.userId;

    if (!userId) {
      throw new Error('User not authenticated');
    }

    const child = await this.childrenService.update(userId, id, {
      name: input.name,
      birthDate: input.birthDate ? input.birthDate.toISOString() : undefined,
      gender: input.gender,
      photoUrl: input.photoUrl,
      medicalInfo: input.medicalInfo,
    });

    return child as any;
  }

  @Mutation(() => Boolean)
  async deleteChild(
    @Args('id') id: string,
    @Context() context: any,
  ): Promise<boolean> {
    const userId = context.req?.user?.userId;

    if (!userId) {
      throw new Error('User not authenticated');
    }

    await this.childrenService.remove(userId, id);
    return true;
  }
}
