"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/migrations/message-channels-to-service-channels.ts
var message_channels_to_service_channels_exports = {};
__export(message_channels_to_service_channels_exports, {
  default: () => message_channels_to_service_channels_default
});
module.exports = __toCommonJS(message_channels_to_service_channels_exports);
var import_node_fs = __toESM(require("fs"), 1);
var import_glob = require("glob");
var import_node_os = __toESM(require("os"), 1);
var import_gray_matter = __toESM(require("gray-matter"), 1);
var import_node_path = __toESM(require("path"), 1);
var DISABLE_CHANNEL_MIGRATION_ENV = "EVENTCATALOG_DISABLE_CHANNEL_MIGRATION";
var isChannelMigrationDisabled = () => {
  return ["true", "1", "yes"].includes((process.env[DISABLE_CHANNEL_MIGRATION_ENV] ?? "").toLowerCase());
};
var message_channels_to_service_channels_default = async (dir) => {
  if (isChannelMigrationDisabled()) {
    return { status: "skipped", message: `Channel migration disabled by ${DISABLE_CHANNEL_MIGRATION_ENV}` };
  }
  const PROJECT_DIR = import_node_path.default.join(dir || process.env.PROJECT_DIR);
  const messages = await (0, import_glob.glob)(
    [
      "**/events/*/index.mdx",
      "**/events/*/index.md",
      "**/events/*/versioned/*/index.mdx",
      "**/events/*/versioned/*/index.md",
      // commands
      "**/commands/*/index.mdx",
      "**/commands/*/index.md",
      "**/commands/*/versioned/*/index.mdx",
      "**/commands/*/versioned/*/index.md",
      // queries
      "**/queries/*/index.mdx",
      "**/queries/*/index.md",
      "**/queries/*/versioned/*/index.mdx",
      "**/queries/*/versioned/*/index.md"
    ],
    {
      // const events = await glob(['**/events/*/index.(md|mdx)', '**/events/*/versioned/*/index.(md|mdx)'], {
      cwd: PROJECT_DIR,
      absolute: true,
      nodir: true,
      windowsPathsNoEscape: import_node_os.default.platform() == "win32",
      ignore: ["node_modules/**", "**/dist/**", "**/teams", "**/users", "**/package.json", "**/Dockerfile"]
    }
  );
  const services = await (0, import_glob.glob)(
    [
      "**/services/*/index.mdx",
      "**/services/*/index.md",
      "**/services/*/versioned/*/index.mdx",
      "**/services/*/versioned/*/index.md"
    ],
    {
      cwd: PROJECT_DIR,
      absolute: true
    }
  );
  const messagesWithChannels = messages.reduce((acc, message) => {
    const file = import_node_fs.default.readFileSync(message, "utf8");
    const { data } = (0, import_gray_matter.default)(file);
    if (data.channels?.length > 0) {
      acc.push({
        ...data,
        path: message
      });
    }
    return acc;
  }, []);
  if (messagesWithChannels.length === 0) {
    return { status: "success", message: "No messages with channels found in the catalog" };
  }
  const servicesWithChannels = services.reduce((acc, service) => {
    const file = import_node_fs.default.readFileSync(service, "utf8");
    const { data } = (0, import_gray_matter.default)(file);
    const isSending = data.sends?.some((send) => messagesWithChannels.some((message) => message.id === send.id));
    const isReceiving = data.receives?.some(
      (receive) => messagesWithChannels.some((message) => message.id === receive.id)
    );
    if (isSending || isReceiving) {
      acc.push({
        ...data,
        path: service
      });
    }
    return acc;
  }, []);
  for (const service of servicesWithChannels) {
    const file = import_node_fs.default.readFileSync(service.path, "utf8");
    const { data } = (0, import_gray_matter.default)(file);
    const messagesTheServiceSendsThatNeedUpdating = data.sends?.filter((send) => messagesWithChannels.some((message) => message.id === send.id)) ?? [];
    const messagesTheServiceReceivesThatNeedUpdating = data.receives?.filter((receive) => messagesWithChannels.some((message) => message.id === receive.id)) ?? [];
    if (messagesTheServiceSendsThatNeedUpdating.length > 0 || messagesTheServiceReceivesThatNeedUpdating.length > 0) {
      const newSends = (data.sends ?? []).map((send) => {
        const match = messagesWithChannels.find((message) => message.id === send.id);
        if (!match) return send;
        return { ...send, to: (match.channels ?? []).filter((channel) => channel !== null) };
      });
      const newReceives = (data.receives ?? []).map((receive) => {
        const match = messagesWithChannels.find((message) => message.id === receive.id);
        if (!match) return receive;
        return { ...receive, from: (match.channels ?? []).filter((channel) => channel !== null) };
      });
      const newData = {
        ...data,
        ...newSends.length > 0 ? { sends: newSends } : {},
        ...newReceives.length > 0 ? { receives: newReceives } : {}
      };
      import_node_fs.default.writeFileSync(service.path, import_gray_matter.default.stringify(file, newData));
    }
  }
  for (const message of messagesWithChannels) {
    const file = import_node_fs.default.readFileSync(message.path, "utf8");
    const parsed = (0, import_gray_matter.default)(file);
    const { channels, ...newData } = parsed.data;
    import_node_fs.default.writeFileSync(message.path, import_gray_matter.default.stringify(parsed.content, newData));
  }
  console.log("\u2714 Channels migrated to new services API");
};
