import { DynamoDB } from "aws-sdk";

import { initCommonMiddlewares } from "../middlewares";

interface IEvent {
  id: string;
}

interface IActivity {
  id: string;
  type: string;
  datetime: string;
  value: string;
}

const { TABLE_NAME } = process.env;

const ddb = new DynamoDB.DocumentClient();

async function awsHandler(event: IEvent): Promise<IActivity[]> {
  const { id } = event;

  const { Items } = await ddb
    .query({
      TableName: TABLE_NAME,
      KeyConditions: {
        id: {
          AttributeValueList: [id],
          ComparisonOperator: "EQ",
        },
      },
      AttributesToGet: ["type", "timestamp", "value"],
    })
    .promise();

  const activities = (Items || []).map(
    (item) =>
      ({
        type: item.type,
        datetime: new Date(item.timestamp).toISOString(),
        value: item.value,
      } as IActivity),
  );

  return activities;
}

export const handler = initCommonMiddlewares(awsHandler);
