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

const { STAGE, REGION, STATE_MACHINE_PREFIX, ACCOUNT_ID } = process.env;

interface IEvent {
  name: string;
  input: object;
}

interface IResult {
  executionArn: string;
  input: object;
}

const stepFunctions = new StepFunctions();

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

  const arn: string = await createStepFunctionsArn(name);

  const { executionArn } = await stepFunctions
    .startExecution({
      stateMachineArn: arn,
      input: JSON.stringify(input),
    })
    .promise();

  return { executionArn, input };
}

async function createStepFunctionsArn(name: string) {
  return `arn:aws:states:${REGION}:${ACCOUNT_ID}:stateMachine:${STATE_MACHINE_PREFIX}-${name}-${STAGE}`;
}

export const handler = initCommonMiddlewares(awsHandler);
