import { Context } from "aws-lambda";
import { DynamoDB } from "aws-sdk";
import { ItemNotFoundError, PermissionDeniedError } from "../errors";
import { initCommonMiddlewares } from "../middlewares";
interface IEvent {
  name: string;
  namespace?: string;

  // Check permission when user input is defined.
  user?: {
    username: string;
  };
}

interface IResult {
  name: string;
  namespace?: string;
  description: string;
  category: string;
  username: 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 } = event;
  let { namespace } = event;

  if (!namespace) {
    namespace = "none";
  }

  const { Item } = await ddb
    .get({
      TableName: PACKAGE_TABLE_NAME,
      Key: {
        name,
        namespace,
      },
    })
    .promise();

  if (!Item) {
    throw new ItemNotFoundError();
  } else if (user && user.username && user.username !== Item.username) {
    throw new PermissionDeniedError(
      "User is not the owner of the existing package!",
    );
  } else {
    const { description, username, readme, category } = Item as IResult;

    return {
      name: Item.name,
      description,
      namespace: Item.namespace === "none" ? undefined : Item.namespace,
      username,
      readme,
      category,
    };
  }
}

export const handler = initCommonMiddlewares(awsHandler);
