import {
  Args,
  Resolver,
  Query,
  Mutation,
  ResolveField,
  Parent
} from '@nestjs/graphql';

import { DatabaseService } from '../database/database.service';

import {
  Club,
  GameData,
  Group,
  Player,
  PlayerCreateInput,
  PlayerUpdateInput
} from '../@generated/prisma-nestjs-graphql';
import { UseGuards } from '@nestjs/common';
import { JwtAuthGuard } from '../authentication/jwt-auth.guard';

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

  @Query((returns) => Player)
  @UseGuards(JwtAuthGuard)
  public async player(
    @Args('id', { type: () => String }) id: string
  ): Promise<Player | null> {
    return this.$database.player.findFirst({
      where: {
        id
      }
    });
  }

  @Mutation((returns) => Player)
  @UseGuards(JwtAuthGuard)
  public async createPlayer(
    @Args('data', { type: () => PlayerCreateInput }) data: PlayerCreateInput
  ) {
    return this.$database.player.create({ data });
  }

  @Mutation((returns) => Player)
  @UseGuards(JwtAuthGuard)
  public async updatePlayer(
    @Args('id', { type: () => String }) id: string,
    @Args('data', { type: () => PlayerUpdateInput }) data: PlayerUpdateInput
  ): Promise<Player> {
    return this.$database.player.update({
      where: {
        id
      },
      data
    });
  }

  @ResolveField()
  public async owner(@Parent() player: Player): Promise<Club | null> {
    const { ownerId } = player;
    return this.$database.club.findFirst({
      where: {
        ownerId
      }
    });
  }

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

  @ResolveField()
  public async group(@Parent() player: Player): Promise<Group | null> {
    const { groupId } = player;
    return this.$database.group.findFirst({
      where: {
        id: groupId
      }
    });
  }
}
