import { DocumentClient } from "aws-sdk/clients/dynamodb";
import { initCommonMiddlewares } from "../middlewares";
import { IPlatformRecord } from "./contract";

interface IEvent {}

interface IPlatformRelease {
  codename: string;
  dockerImage: string;
}
interface IResultItem {
  os: string;
  dist: string;
  icon: { id: string };
  releases: IPlatformRelease[];
}

interface IResult {}

const { PLATFORM_TABLE_NAME } = process.env;

const ddb = new DocumentClient();

async function awsHandler(event: IEvent): Promise<IResult> {
  const {} = event;

  const { Items } = await ddb
    .scan({
      TableName: PLATFORM_TABLE_NAME,
    })
    .promise();

  const distrosIndex = Items.reduce((distros, distro: IPlatformRecord) => {
    const key = `${distro.os}:${distro.dist}`;
    if (distros[key] === undefined) {
      distros[key] = {
        os: distro.os,
        dist: distro.dist,
        icon: distro.icon,
        releases: [],
      };
    }
    distros[key].releases.push({
      codename: distro.codename,
      dockerImage: distro.dockerImage,
    });
    return distros;
  }, {});

  return Object.keys(distrosIndex).map((key) => distrosIndex[key]);
}

export const handler = initCommonMiddlewares(awsHandler);
