"use strict";

// src/migrations/20221117151200_add_detail_columns_to_component_version.js
var path = require("path");
var fs = require("fs");
exports.default = async function(db, logger) {
  await db.query(`ALTER TABLE component_version add display_name varchar not null default '';`);
  await db.query(`ALTER TABLE component_version add description varchar not null default '';`);
  await db.query(`ALTER TABLE component_version add icon jsonb;`);
  const versions = await db.query(`select * from component_version`);
  const dataMount = process.env.DATA_MOUNT_POINT;
  if (dataMount === void 0) {
    throw new Error(`DATA_MOUNT_POINT is undefined`);
  }
  for (const row of versions.rows) {
    logger.info(dataMount, row.component_name, row.version, "manifest.json");
    const manifestPath = path.join(dataMount, row.component_name, row.version, "manifest.json");
    if (fs.existsSync(manifestPath)) {
      logger.info(`found manifest ${manifestPath}`);
      const manifestString = fs.readFileSync(manifestPath, {
        encoding: "utf-8"
      });
      const manifest = JSON.parse(manifestString);
      logger.info(`adding ${manifest.displayName} ${manifest.description} ${manifest.icon} from manifest`);
      let paramIndex = 1;
      const params = [];
      let setClause = `SET display_name=$${paramIndex++}, description=$${paramIndex++}`;
      params.push(manifest.displayName ?? "");
      params.push(manifest.description ?? "");
      if (manifest.icon) {
        setClause = `${setClause}, icon=$${paramIndex++}`;
        params.push(JSON.stringify(manifest.icon));
      }
      let sql = `UPDATE component_version ${setClause} WHERE component_name=$${paramIndex++} and version=$${paramIndex++}`;
      params.push(`${manifest.namespace}/${manifest.name}`);
      params.push(manifest.version);
      await db.query(sql, params);
    }
  }
};
