import { Lambda } from "aws-sdk";

const lambda = new Lambda();

const { SERVICE_NAME, STAGE } = process.env;

export async function invokeService(
  serviceName: string,
  functionName: string,
  params: any,
) {
  const { Payload, StatusCode } = await lambda
    .invoke({
      FunctionName: `${SERVICE_NAME}-${serviceName}-${STAGE}-${functionName}`,
      Payload: JSON.stringify(params),
    })
    .promise();

  if (StatusCode === 200) {
    const response = JSON.parse(Payload.toString());
    if (response.errorMessage) {
      throw new Error(response.errorMessage);
    } else {
      return response;
    }
  } else {
    throw new Error("Failed to invoke service.");
  }
}
