import { S3 } from "aws-sdk";
import { PutObjectOutput } from "aws-sdk/clients/s3";
import * as md5 from "md5";
import { v4 } from "uuid";
import { initCommonMiddlewares } from "../middlewares";

interface IEvent {
  dir: string;
  content: string; // base64 stringified content
}

interface IResult {
  id: string;
  response: PutObjectOutput;
}

const { SERVICE_NAME, STAGE, ASSETS_BUCKET } = process.env;

const s3 = new S3();

async function awsHandler(event: IEvent): Promise<IResult> {
  const { dir, content } = event;

  const uid = `${dir}/${v4()}:asset:${md5(SERVICE_NAME + STAGE)}`;

  const response = await s3
    .putObject({
      Bucket: ASSETS_BUCKET,
      Body: content,
      Key: uid,
    })
    .promise();

  return { id: uid, response };
}

export const handler = initCommonMiddlewares(awsHandler);
