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

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

interface IPackageResult {
  name: string;
  namespace?: string;
  description: string;
  category: string;
}

const { PACKAGE_TABLE_NAME } = process.env;

const ddb = new DynamoDB.DocumentClient();

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

  const { Items } = await ddb
    .query({
      TableName: PACKAGE_TABLE_NAME,
      IndexName: "userIndex",
      KeyConditions: {
        username: {
          AttributeValueList: [user.username],
          ComparisonOperator: "EQ",
        },
      },
      AttributesToGet: ["name", "namespace", "description", "category"],
    })
    .promise();

  return (Items || []).map(
    ({ name, namespace, description, category }: IPackageResult) =>
      ({
        name,
        namespace,
        description,
        category,
      } as IPackageResult),
  );
}

export const handler = initCommonMiddlewares(awsHandler);
