import { Context } from "aws-lambda";
import { DynamoDB } from "aws-sdk";
import { initCommonMiddlewares } from "../middlewares";

interface IEvent {
  name: string;
  namespace?: string;
  description: string;
  category: string;
  readme: {
    id: string;
  };
  user: {
    username: string;
  };
}

interface IResult {
  name: string;
  description: string;
  category: string;
  namespace?: string;
  readme: {
    id: string;
  };
}

const { PACKAGE_TABLE_NAME } = process.env;

const ddb = new DynamoDB.DocumentClient();

async function awsHandler(event: IEvent, context: Context): Promise<IResult> {
  const {
    user,
    name,
    description,
    readme: { id },
    namespace,
    category,
  } = event;

  await ddb
    .put({
      TableName: PACKAGE_TABLE_NAME,
      Item: {
        name,
        namespace: namespace || "none",
        username: user.username,
        description,
        readme: { id },
        category,
      },
    })
    .promise();

  return {
    name,
    description,
    readme: { id },
    category,
    namespace: namespace || "none",
  };
}

export const handler = initCommonMiddlewares(awsHandler);
