import { ApolloServer } from "apollo-server/dist";
import { Resolvers, ChangePizzaDto, ChangeToppingDto } from "./generated/graphql";
import { pizzaSchema } from "./schema/schema";
import { PizzaResolver } from "./resolver/pizza-resolver";
import { ToppingResolver } from "./resolver/topping-resolver";

const resolvers: Resolvers = {
    Topping: {
        id: (root, args, context) => {
            return root.id
        },
        name: (root, args, context) => {
            return root.name
        },
    },
    Pizza: {
        id: (root, args, context) => {
            return root.id
        },
        name: (root, args, context) => {
            return root.name
        },
        toppings: (root, args, context) => {
            return root.toppings
        },
    },
    Query: {
        getPizzaById: (root, args, context) => {
            return PizzaResolver.getById(args.pizzaId);
        },
        getPizzaByName: (root, args, context) => {
            return PizzaResolver.getByName(args.pizzaName);
        },
        listPizza: (root, args, context) => {
            return PizzaResolver.list();
        },
        getToppingById: (root, args, context) => {
            return ToppingResolver.getById(args.toppingId);
        },
        getToppingByName: (root, args, context) => {
            return ToppingResolver.getByName(args.toppingName);
        },
        listTopping: (root, args, context) => {
            return ToppingResolver.list();
        },
    },
    Mutation: {
        createPizza: (root, args, context) => {
            return PizzaResolver.create(args.createPizzaDto as ChangePizzaDto);
        },
        updatePizza: (root, args, context) => {
            return PizzaResolver.update(args.pizzaId, args.updatedPizzaDto as ChangePizzaDto);
        },
        createTopping: (root, args, context) => {
            return ToppingResolver.create(args.createToppingDto as ChangeToppingDto);
        },
        updateTopping: (root, args, context) => {
            return ToppingResolver.update(args.toppingId, args.updatedToppingDto as ChangeToppingDto);
        },
    },
    Subscription: {
        pizzasChanged: {
            subscribe: () => PizzaResolver.pizzaEvent.asyncIterator(PizzaResolver.events.PIZZA_CHANGED)

        },
        toppingsChanged: {
            subscribe: () => ToppingResolver.toppingEvent.asyncIterator(ToppingResolver.events.TOPPING_CHANGED)
        },
    }
}

const server = new ApolloServer({
    typeDefs: pizzaSchema,
    resolvers: resolvers as any,
});

server.listen().then(({ url, subscriptionsUrl }) => {
    console.log(`🚀 Server ready at ${url}`)
    console.log(`🚀 Subscriptions ready at ${subscriptionsUrl}`);
});