import { UseGuards } from '@nestjs/common';
import { Parent, Query, ResolveField } from '@nestjs/graphql';
import { Resolver } from '@nestjs/graphql';

import { Club, Player, User } from '../@generated/prisma-nestjs-graphql';
import { DatabaseService } from '../database/database.service';
import { CurrentUser } from '../current-user.decorator';
import { GqlJwtAuthGuard } from '../authentication/gql-jwt-auth.guard';

@Resolver((of: any) => User)
export class UserResolver {
  constructor(private readonly $database: DatabaseService) {}

  @UseGuards(GqlJwtAuthGuard)
  @Query((returns) => User)
  public async user(@CurrentUser() user: User): Promise<User | null> {
    const { id } = user;
    return this.$database.user.findUnique({
      where: {
        id
      }
    });
  }

  @ResolveField()
  public async clubs(@Parent() user: User): Promise<Club[]> {
    const { id } = user;
    return this.$database.club.findMany({
      where: {
        owner: {
          id
        }
      }
    });
  }

  @ResolveField()
  public async players(@Parent() user: User): Promise<Player[]> {
    const { id } = user;
    return this.$database.player.findMany({
      where: {
        owner: {
          id
        }
      }
    });
  }
}
