import { Context } from "aws-lambda";
import { DynamoDB } from "aws-sdk";
import { createPackageHash } from "../helpers";
import { initCommonMiddlewares } from "../middlewares";
import { IPlatform, IScriptRecord } from "./global";

interface IEvent {
  package: {
    name: string;
    namespace?: string;
  };
}

interface IScriptMetadata {
  version: string;
  platform: IPlatform[];
}

type IResult = IScriptMetadata[];

const { TABLE_NAME } = process.env;

const ddb = new DynamoDB.DocumentClient();

async function awsHandler(event: IEvent, context: Context): Promise<IResult> {
  const { package: pkg } = event;

  const packageHash = createPackageHash(pkg);

  const { Items } = await ddb
    .query({
      TableName: TABLE_NAME,
      KeyConditions: {
        packageHash: {
          AttributeValueList: [packageHash],
          ComparisonOperator: "EQ",
        },
      },
      AttributesToGet: ["version", "platform"],
    })
    .promise();

  return (Items || []).map(
    ({ version, platform }: IScriptRecord) =>
      ({
        version,
        platform: platform || [],
      } as IScriptMetadata),
  );
}

export const handler = initCommonMiddlewares(awsHandler);
