import {
    Args,
    Mutation,
    Parent,
    Query,
    ResolveField,
    Resolver,
} from '@nestjs/graphql';
import { Group } from './models/group.model';
import { PrismaService } from '../prisma/prisma.service';
import { GraphQLString } from 'graphql';
import seedWords from 'mnemonic-words';
import { NotFoundException } from '@nestjs/common';

@Resolver(() => Group)
export class GroupResolver {
    constructor(private prismaService: PrismaService) {}

    @Mutation(() => Group)
    async createGroup(
        @Args({ name: 'name', type: () => GraphQLString }) name: string,
    ) {
        function generateWord() {
            return seedWords[Math.round(Math.random() * seedWords.length)];
        }

        const code = [
            generateWord(),
            generateWord(),
            generateWord(),
            generateWord(),
        ].join('-');

        return this.prismaService.group.create({
            data: {
                name,
                code,
            },
        });
    }

    @Query(() => Group)
    async getGroup(
        @Args({ name: 'code', type: () => GraphQLString }) code: string,
    ) {
        const group = this.prismaService.group.findFirst({
            where: { code },
            include: { unlocks: true },
        });

        if (!group) throw new NotFoundException();

        return group;
    }

    @ResolveField('unlocks')
    async unlocks(@Parent() group: Group) {
        const result = await this.prismaService.group.findFirst({
            where: { id: group.id },
            select: { unlocks: true },
        });

        return result.unlocks;
    }
}