import { Context } from "aws-lambda";
import { CognitoIdentityServiceProvider } from "aws-sdk";
import { initCommonMiddlewares } from "../middlewares";

interface IEvent {
  username: string;
}

interface IResult {
  groups: string[];
}

const { POOL_ID } = process.env;

const userProvider = new CognitoIdentityServiceProvider();

async function awsHandler(event: IEvent, context: Context): Promise<IResult> {
  const { username } = event;

  const { Groups } = await userProvider
    .adminListGroupsForUser({
      UserPoolId: POOL_ID,
      Username: username,
    })
    .promise();

  return { groups: Groups.map((group) => group.GroupName) };
}

export const handler = initCommonMiddlewares(awsHandler);
