import { DynamoDB } from "aws-sdk";
import { initCommonMiddlewares } from "../middlewares";
import { DispatchSnsAfter } from "../middlewares/sns";

interface IEvent {
  id: string;
  type: string;
  value: string;
}

interface IItemRecord {
  id: string;
  type: string;
  timestamp: number;
  value: string;
}

const { TABLE_NAME, LOG_TOPIC_ARN } = process.env;

const ddb = new DynamoDB.DocumentClient();

async function awsHandler(event: IEvent): Promise<IItemRecord> {
  const { id, type, value } = event;

  const item: IItemRecord = {
    id,
    type,
    timestamp: Date.now(),
    value,
  };

  await ddb
    .put({
      TableName: TABLE_NAME,
      Item: item,
    })
    .promise();

  return item;
}

export const handler = initCommonMiddlewares(awsHandler).use(
  DispatchSnsAfter({
    topic: LOG_TOPIC_ARN,
  }),
);
