import { Resolver, Mutation, Args, Context } from '@nestjs/graphql';
import { UseGuards } from '@nestjs/common';
import { ActivityGQLType } from '../types/activity.type';
import { CreateActivityInput, UpdateActivityInput } from '../inputs/activity.input';
import { TrackingService } from '../../modules/tracking/tracking.service';
import { GqlAuthGuard } from '../guards/gql-auth.guard';

@Resolver(() => ActivityGQLType)
@UseGuards(GqlAuthGuard)
export class ActivityResolver {
  constructor(private readonly trackingService: TrackingService) {}

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

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

    const activity = await this.trackingService.create(userId, input.childId, {
      type: input.type,
      startedAt: input.startedAt.toISOString(),
      endedAt: input.endedAt ? input.endedAt.toISOString() : undefined,
      notes: input.notes,
      metadata: input.metadata,
    });

    return activity as any;
  }

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

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

    const activity = await this.trackingService.update(userId, id, {
      type: input.type,
      startedAt: input.startedAt ? input.startedAt.toISOString() : undefined,
      endedAt: input.endedAt ? input.endedAt.toISOString() : undefined,
      notes: input.notes,
      metadata: input.metadata,
    });

    return activity as any;
  }

  @Mutation(() => Boolean)
  async deleteActivity(
    @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.trackingService.remove(userId, id);
    return true;
  }
}
