"use strict";

// src/migrations/20230210143300_lowercase_all_uri_names.js
var fsp = require("fs/promises");
var { readdirSync } = require("fs");
var path = require("path");
exports.default = async function(db, _logger) {
  var _a, _b;
  await db.query(`ALTER TABLE component drop constraint IF EXISTS component_name_is_lower`);
  await db.query(`ALTER TABLE component_version drop constraint IF EXISTS component_version_component_name_is_lower`);
  await db.query(`ALTER TABLE component_set drop constraint IF EXISTS component_set_web_path_is_lower`);
  await db.query(`UPDATE component SET name = lower(name)`);
  await db.query(`ALTER TABLE component add constraint component_name_is_lower check (name = lower(name))`);
  await db.query(`UPDATE component_version SET component_name = lower(component_name)`);
  await db.query(
    `ALTER TABLE component_version add constraint component_version_component_name_is_lower check (component_name = lower(component_name))`
  );
  await db.query(`UPDATE component_set SET web_path = lower(web_path)`);
  await db.query(
    `ALTER TABLE component_set add constraint component_set_web_path_is_lower check (web_path = lower(web_path))`
  );
  for await (const { manifest, manifestPath } of getComponentManifests()) {
    const { namespace, name } = manifest;
    await fsp.writeFile(
      manifestPath,
      JSON.stringify(
        /** @type {import('@squiz/dx-json-schema-lib').MANIFEST_MODELS.v1.ComponentManifest} */
        {
          ...manifest,
          namespace: namespace.toLowerCase(),
          name: name.toLowerCase(),
          functions: (_a = manifest.functions) == null ? void 0 : _a.map((fn) => ({
            ...fn,
            name: fn.name.toLowerCase()
          })),
          mainFunction: (_b = manifest.mainFunction) == null ? void 0 : _b.toLowerCase()
        },
        null,
        2
      )
    );
    const versionDirectory = path.dirname(manifestPath);
    const componentNameDirectory = path.dirname(versionDirectory);
    const namespaceDirectory = path.dirname(componentNameDirectory);
    const lowerName = path.basename(componentNameDirectory).toLowerCase();
    const lowerNamespace = path.basename(namespaceDirectory).toLowerCase();
    await fsp.rename(componentNameDirectory, path.resolve(namespaceDirectory, lowerName));
    await fsp.rename(namespaceDirectory, path.resolve(path.dirname(namespaceDirectory), lowerNamespace));
  }
};
async function* getComponentManifests() {
  var _a;
  for (const componentDirectory of listDirectories(process.env.DATA_MOUNT_POINT)) {
    const manifestPath = path.resolve(componentDirectory, "manifest.json");
    const manifest = await tryReadManifest(manifestPath);
    if ((_a = manifest == null ? void 0 : manifest.$schema) == null ? void 0 : _a.match(/v1\.json#?$/)) {
      yield { manifest, manifestPath };
    }
  }
}
function* listDirectories(filePath, nesting = 3) {
  let files;
  try {
    files = readdirSync(filePath, { withFileTypes: true });
  } catch (err) {
    if (err.code !== "ENOENT") {
      throw err;
    }
    return;
  }
  for (const file of files) {
    if (file.name === "manifest.json")
      yield filePath;
    else if (!file.isDirectory())
      continue;
    else if (nesting === 0)
      yield filePath;
    else
      yield* listDirectories(path.resolve(filePath, file.name), nesting - 1);
  }
}
async function tryReadManifest(manifestPath) {
  try {
    return JSON.parse(await fsp.readFile(manifestPath, { encoding: "utf-8" }));
  } catch (_e) {
    return null;
  }
}
