import { SNSEvent, SNSEventRecord } from "aws-lambda";
import { initCommonMiddlewares } from "../middlewares";
import { invokeService } from "./helpers";

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

async function awsHandler(event: SNSEvent): Promise<void> {
  const promises = event.Records.map((record) => resolveToDocuments(record));
  const documents = await Promise.all(promises);

  return await invokeService("search", "indexing", {
    indexName: "activities",
    type: "activity",
    data: documents,
  });
}

async function resolveToDocuments(record: SNSEventRecord) {
  const { id, timestamp, type, value }: IMessage = JSON.parse(
    record.Sns.Message,
  );

  return {
    packageHash: id,
    datetime: new Date(timestamp).toISOString(),
    type,
    value,
  };
}

export const handler = initCommonMiddlewares(awsHandler);
