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

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

interface IResult {
  status: ChallengeNameType | "LOGGED_IN";
  session?: string;
  accessToken?: string;
  idToken?: string;
}
const { POOL_CLIENT_ID } = process.env;

const userProvider = new CognitoIdentityServiceProvider();

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

  const { ChallengeName, Session, AuthenticationResult } = await userProvider
    .respondToAuthChallenge({
      ChallengeName: "NEW_PASSWORD_REQUIRED",
      ClientId: POOL_CLIENT_ID,
      Session: session,
      ChallengeResponses: {
        USERNAME: username,
        NEW_PASSWORD: password,
      },
    })
    .promise();

  if (ChallengeName) {
    return {
      status: ChallengeName,
      session: Session,
    };
  } else if (AuthenticationResult && AuthenticationResult.AccessToken) {
    return {
      status: "LOGGED_IN",
      accessToken: AuthenticationResult.AccessToken,
      idToken: AuthenticationResult.IdToken,
    };
  } else {
    // unhandled login results
    console.error(
      "Unhandled login response: ",
      JSON.stringify({ ChallengeName, Session, AuthenticationResult }),
    );
    throw new Error("Unhandled login response");
  }
}

export const handler = initCommonMiddlewares(awsHandler);
