import { CliLeaf, CliStringInput } from '@alwaysai/alwayscli';
import { yesCliInput } from '../../cli-inputs';
import { fetchAppReleaseHistoryComponent } from '../../components/release';
import { echo } from '../../util';

export const getAppReleaseHistoryCliLeaf = CliLeaf({
  name: 'list',
  description: 'Retrieve information about the application release',
  namedInputs: {
    yes: yesCliInput,
    project: CliStringInput({
      description: 'Project ID',
      required: true
    })
  },
  async action(_, opts) {
    const { yes, project } = opts;
    const releaseHistory = await fetchAppReleaseHistoryComponent({
      yes,
      project
    });

    if (releaseHistory.length === 0) {
      echo(`No releases found for project ${project}`);
      return;
    }

    const releaseHistoryTable = releaseHistory.reduce((acc, release) => {
      const { version, hash, name, created_at, size } = release;
      const sizeWithUnits = size + ' B';
      acc[version] = { name, hash, created_at, size: sizeWithUnits };
      return acc;
    }, []);

    echo(`Retrieved application history for project ${project}`);
    console.table(releaseHistoryTable);
  }
});
