/**
 * This file is part of the NocoBase (R) project.
 * Copyright (c) 2020-2024 NocoBase Co., Ltd.
 * Authors: NocoBase Team.
 *
 * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
 * For more information, please refer to: https://www.nocobase.com/agreement.
 */

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);
var server_exports = {};
__export(server_exports, {
  PluginUISchemaStorageServer: () => PluginUISchemaStorageServer,
  compile: () => compile,
  default: () => server_default
});
module.exports = __toCommonJS(server_exports);
var import_database = require("@nocobase/database");
var import_server = require("@nocobase/server");
var import_utils = require("@nocobase/utils");
var import_model = require("./model");
var import_repository = __toESM(require("./repository"));
const compile = (title) => (title || "").replace(/{{\s*t\(["|'|`](.*)["|'|`]\)\s*}}/g, "$1");
function extractFields(obj) {
  var _a, _b, _c, _d, _e;
  const fields = [
    obj.title,
    obj.description,
    (_a = obj["x-component-props"]) == null ? void 0 : _a.title,
    (_b = obj["x-component-props"]) == null ? void 0 : _b.description,
    (_c = obj["x-decorator-props"]) == null ? void 0 : _c.title,
    (_d = obj["x-decorator-props"]) == null ? void 0 : _d.description
  ];
  const content = (_e = obj["x-component-props"]) == null ? void 0 : _e.content;
  if (typeof content === "string") {
    const regex = /\{\{\s*t\s+['"]([^'"]+)['"]\s*\}\}/g;
    let match;
    while ((match = regex.exec(content)) !== null) {
      fields.push(match[1]);
    }
  }
  return fields.filter((value) => value !== void 0 && value !== "");
}
class PluginUISchemaStorageServer extends import_server.Plugin {
  registerRepository() {
    this.app.db.registerRepositories({
      FlowModelRepository: import_repository.default
    });
  }
  async beforeLoad() {
    const db = this.app.db;
    this.app.db.registerModels({ MagicAttributeModel: import_database.MagicAttributeModel, FlowSchemaModel: import_model.FlowSchemaModel });
    this.registerRepository();
    this.app.acl.registerSnippet({
      name: "ui.flowModels",
      actions: ["flowModels:*"]
    });
    db.on("flowModels.beforeCreate", function setUid(model) {
      if (!model.get("name")) {
        model.set("name", (0, import_utils.uid)());
      }
    });
    this.app.localeManager.registerSource("flow-models", {
      title: (0, import_utils.tval)("Flow models"),
      collections: [
        {
          collection: "flowModels",
          getTexts: (model) => extractFields(model.toJSON()).map((field) => compile(field)).filter(Boolean).map((text) => ({ text, module: `resources.ui-schema-storage` }))
        }
      ]
    });
    db.on("flowModels.afterCreate", async function insertSchema(model, options) {
      const { transaction } = options;
      const uiSchemaRepository = db.getCollection("flowModels").repository;
      const context = options.context;
      if (context == null ? void 0 : context.disableInsertHook) {
        return;
      }
      await uiSchemaRepository.insert(model.toJSON(), {
        transaction
      });
    });
    db.on("flowModels.afterUpdate", async function patchSchema(model, options) {
      const { transaction } = options;
      const uiSchemaRepository = db.getCollection("flowModels").repository;
      await uiSchemaRepository.patch(model.toJSON(), {
        transaction
      });
    });
    db.on("flowModels.afterDestroy", async function patchSchema(model, options) {
      const { transaction } = options;
      const uiSchemaRepository = db.getCollection("flowModels").repository;
      await uiSchemaRepository.remove(model.get("name"), { transaction });
    });
    this.app.resourceManager.define({
      name: "flowModels",
      actions: {
        findOne: async (ctx, next) => {
          const { uid: uid2, parentId, subKey, includeAsyncNode = false } = ctx.action.params;
          const repository = ctx.db.getRepository("flowModels");
          if (uid2) {
            ctx.body = await repository.findModelById(uid2, { includeAsyncNode });
          } else if (parentId) {
            ctx.body = await repository.findModelByParentId(parentId, { subKey, includeAsyncNode });
          }
          await next();
        },
        duplicate: async (ctx, next) => {
          const { uid: uid2 } = ctx.action.params;
          const repository = ctx.db.getRepository("flowModels");
          const duplicated = await repository.duplicate(uid2);
          ctx.body = duplicated;
          await next();
        },
        attach: async (ctx, next) => {
          const { uid: uid2, parentId, subKey, subType, position } = ctx.action.params;
          const repository = ctx.db.getRepository("flowModels");
          const attached = await repository.attach(String(uid2 || "").trim(), {
            parentId: String(parentId || "").trim(),
            subKey: String(subKey || "").trim(),
            subType,
            position
          });
          ctx.body = attached;
          await next();
        },
        move: async (ctx, next) => {
          const { sourceId, targetId, position } = ctx.action.params;
          const repository = ctx.db.getRepository("flowModels");
          await repository.move({ sourceId, targetId, position });
          ctx.body = "ok";
          await next();
        },
        save: async (ctx, next) => {
          const { values } = ctx.action.params;
          const repository = ctx.db.getRepository("flowModels");
          const uid2 = await repository.upsertModel(values);
          ctx.body = uid2;
          await next();
        },
        destroy: async (ctx, next) => {
          const { filterByTk } = ctx.action.params;
          const repository = ctx.db.getRepository("flowModels");
          await repository.remove(filterByTk);
          ctx.body = "ok";
          await next();
        }
      }
    });
    this.app.acl.allow("flowModels", ["findOne"], "loggedIn");
  }
  async load() {
    const getSourceAndTargetForRemoveAction = async (ctx) => {
      const { filterByTk } = ctx.action.params;
      return {
        targetCollection: "flowModels",
        targetRecordUK: filterByTk
      };
    };
    const getSourceAndTargetForInsertAdjacentAction = async (ctx) => {
      var _a, _b;
      return {
        targetCollection: "flowModels",
        targetRecordUK: (_b = (_a = ctx.request.body) == null ? void 0 : _a.options) == null ? void 0 : _b["uid"]
      };
    };
    const getSourceAndTargetForPatchAction = async (ctx) => {
      var _a;
      return {
        targetCollection: "flowModels",
        targetRecordUK: (_a = ctx.request.body) == null ? void 0 : _a["uid"]
      };
    };
    this.app.auditManager.registerActions([
      { name: "flowModels:remove", getSourceAndTarget: getSourceAndTargetForRemoveAction },
      { name: "flowModels:insertAdjacent", getSourceAndTarget: getSourceAndTargetForInsertAdjacentAction },
      { name: "flowModels:patch", getSourceAndTarget: getSourceAndTargetForPatchAction }
    ]);
  }
}
var server_default = PluginUISchemaStorageServer;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  PluginUISchemaStorageServer,
  compile
});
