// graphql.js

import { ApolloServer } from "apollo-server-lambda";
import resolvers from "../resolvers/private";
import definitions from "../schema/private.gql";
import { getUserGroups } from "../resolvers/invokers/user";
import { APIGatewayEvent, APIGatewayEventRequestContext } from "aws-lambda";

interface IPrivateRequestContext extends APIGatewayEventRequestContext {
  authorizer: {
    claims: {
      sub: string;
    };
  };
}

interface IPrivateAPIGatewayEvent extends APIGatewayEvent {
  requestContext: IPrivateRequestContext;
}

export interface IPrivateResolverContext {
  groups: string[];
  functionName: string;
  headers: { [name: string]: string };
}

const server = new ApolloServer({
  context: async (args) => {
    const event: IPrivateAPIGatewayEvent = args.event;

    const { context } = args;
    const {
      authorizer: {
        claims: { sub },
      },
    } = event.requestContext;
    const { groups } = await getUserGroups.execute({ username: sub });

    return {
      groups,
      functionName: context.functionName,
      headers: event.headers,
    };
  },
  introspection: true,
  playground: true,
  resolvers,
  typeDefs: definitions,
});

export const handler = server.createHandler({
  cors: {
    credentials: true,
    origin: true,
  },
});
