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

interface IEvent {
  username: string;
  password: string;
}

interface IResult {
  userConfirmed: boolean;
  deliveryMedium?: DeliveryMediumType;
}

const { POOL_CLIENT_ID } = process.env;

const userProvider = new CognitoIdentityServiceProvider();

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

  const { UserConfirmed, CodeDeliveryDetails } = await userProvider
    .signUp({
      ClientId: POOL_CLIENT_ID,
      Password: password,
      Username: username,
    })
    .promise();
  return {
    userConfirmed: UserConfirmed,
    deliveryMedium: CodeDeliveryDetails
      ? CodeDeliveryDetails.DeliveryMedium
      : null,
  };
}

export const handler = initCommonMiddlewares(awsHandler);
