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

interface IEvent {
  namespace?: string;
  user: {
    username: string;
  };
}

interface IResult {}

const { NAMESPACE_TABLE_NAME } = process.env;

const ddb = new DynamoDB.DocumentClient();

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

  if (!namespace || namespace === "none") {
    // no namespace defined
    return {};
  }

  await ddb
    .put({
      TableName: NAMESPACE_TABLE_NAME,
      Item: {
        namespace,
        username: user.username,
      },
      ConditionExpression:
        "attribute_not_exists(username) or username=:username",
      ExpressionAttributeValues: {
        ":username": user.username,
      },
    })
    .promise()
    .catch((error) => {
      const { code, message } = error;
      if (code === "ConditionalCheckFailedException") {
        throw new NamespaceAlreadyTakenError(message);
      } else {
        throw error;
      }
    });

  return {};
}

export const handler = initCommonMiddlewares(awsHandler);
