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

interface IEvent {
  refreshToken: string;
}

interface IResult {
  status: ChallengeNameType | "LOGGED_IN";
  session?: string;
  accessToken?: string;
  idToken?: string;
  refreshToken?: string;
}

const { POOL_CLIENT_ID } = process.env;

const userProvider = new CognitoIdentityServiceProvider();

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

  const { ChallengeName, Session, AuthenticationResult } = await userProvider
    .initiateAuth({
      ClientId: POOL_CLIENT_ID,
      AuthFlow: "REFRESH_TOKEN_AUTH",
      AuthParameters: {
        REFRESH_TOKEN: refreshToken,
      },
    })
    .promise();

  if (ChallengeName) {
    return {
      status: ChallengeName,
      session: Session,
    };
  } else if (AuthenticationResult && AuthenticationResult.AccessToken) {
    return {
      status: "LOGGED_IN",
      accessToken: AuthenticationResult.AccessToken,
      idToken: AuthenticationResult.IdToken,
      refreshToken: AuthenticationResult.RefreshToken,
    };
  } 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);
