import {Args, Parent, Query, ResolveField, Resolver} from "@nestjs/graphql";
import {Agent} from "./models/agent.model";
import {PrismaService} from "../prisma/prisma.service";
import {GraphQLString} from "graphql";
import {NotFoundException} from "@nestjs/common";

@Resolver(() => Agent)
export class AgentResolver {

    constructor(
        private prismaService: PrismaService,
    ) {}

    @Query(() => [Agent])
    listAgents() {
        return this.prismaService.agent.findMany({
            include: {
                unlocks: true,
                entries: true,
            },
        });
    }

    @Query(() => Agent)
    async getAgent(
        @Args({ name: 'code', type: () => GraphQLString }) code: string,
    ) {
        const agent = await this.prismaService.agent.findFirst({
            where: { slug: code },
        });

        if (!agent)
            throw new NotFoundException();

        return agent;
    }

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

        return result.unlocks;
    }

    @ResolveField('entries')
    async entries(@Parent() entry: Agent) {
        const result = await this.prismaService.agent.findFirst({
            where: { id: entry.id },
            select: { entries: true },
        });

        return result.entries;
    }

}