"use strict";

// src/migrations/20230218121212_add_component_set_rules.js
exports.default = async function(dbClient) {
  const result = await dbClient.query("select * from component_set_component_version where status='active'");
  const rows = result.rows ?? [];
  const componentSetVersions = {};
  for (const row of rows) {
    if (componentSetVersions[row.component_set_web_path] === void 0) {
      componentSetVersions[row.component_set_web_path] = {};
    }
    if (componentSetVersions[row.component_set_web_path][row.component_name] === void 0) {
      componentSetVersions[row.component_set_web_path][row.component_name] = [];
    }
    componentSetVersions[row.component_set_web_path][row.component_name].push(row.component_version);
  }
  for (const [componentSet, components] of Object.entries(componentSetVersions)) {
    for (const [componentName, componentVersions] of Object.entries(components)) {
      await dbClient.query(
        `insert into component_set_rule(component_name, component_set_web_path, version_pattern) values('${componentName}', '${componentSet}', '${componentVersions.join(" || ")}') ON CONFLICT (component_name, component_set_web_path) DO NOTHING`
      );
    }
  }
};
