import { Context } from "aws-lambda";
import { DynamoDB } from "aws-sdk";
import { NotFoundError } from "../errors";
import { createPackageHash } from "../helpers";
import { initCommonMiddlewares } from "../middlewares";
import { IScript } from "./global";

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

const { TABLE_NAME } = process.env;

const ddb = new DynamoDB.DocumentClient();

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

  const packageHash = createPackageHash(pkg);

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

  if (!Items || !Items.length) {
    throw new NotFoundError("Script not found!");
  }

  const [item] = Items;

  return {
    version: item.version,
    execute: item.execute,
    readme: item.readme,
    description: item.description,
    category: item.category,
    superuser: item.superuser,
    platform: item.platform || [],
    dependencies: item.dependencies || [],
    resolvedDependencies: item.resolvedDependencies || [],
  };
}

export const handler = initCommonMiddlewares(awsHandler);
