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

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

const { TABLE_NAME, CREATE_TOPIC_ARN } = process.env;

const ddb = new DynamoDB.DocumentClient();

async function awsHandler(
  event: IEvent,
  context: Context,
): Promise<IScriptRecord> {
  const {
    version,
    description,
    execute,
    readme,
    superuser,
    package: { name, namespace },
    platform,
    dependencies,
    resolvedDependencies,
    category,
  } = event;

  const packageHash = createPackageHash({ name, namespace });

  const scriptRecord: IScriptRecord = {
    packageHash,
    package: { name, namespace },
    version,
    execute,
    readme,
    description,
    category,
    superuser: superuser || false,
    platform,
    dependencies,
    resolvedDependencies,
  };

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

  return scriptRecord;
}

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