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

interface IEvent {
  accessToken: string;
}

interface IResult {
  username: string;
  email: string;
}

const userProvider = new CognitoIdentityServiceProvider();

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

  const { Username, UserAttributes } = await userProvider
    .getUser({
      AccessToken: accessToken,
    })
    .promise();

  return {
    username: Username,
    email: getAttributeValue("email", UserAttributes),
  };
}

function getAttributeValue(
  attributeName: string,
  userAttributes: AttributeListType,
): string | null {
  const attrs = userAttributes.filter(
    (attribute) => attribute.Name === attributeName,
  );
  if (attrs.length) {
    return attrs[0].Value || null;
  } else {
    return null;
  }
}

export const handler = initCommonMiddlewares(awsHandler);
