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, {
  default: () => PluginFileManager,
  storageTypes: () => import_storages2.default
});
module.exports = __toCommonJS(server_exports);
var import_node_path = require("node:path");
var import_server = require("@tego/server");
var import_actions = __toESM(require("./actions"));
var import_FileModel = require("./FileModel");
var import_storages = require("./storages");
var import_storages2 = __toESM(require("./storages"));
class PluginFileManager extends import_server.Plugin {
  storageType() {
    return "local";
  }
  async loadStorages(options) {
    const repository = this.db.getRepository("storages");
    const storages = await repository.find({
      transaction: options == null ? void 0 : options.transaction
    });
    const map = /* @__PURE__ */ new Map();
    for (const storage of storages) {
      map.set(storage.get("id"), this.parseStorage(storage));
    }
    this.db["_fileStorages"] = map;
  }
  parseStorage(instance) {
    return this.app.environment.renderJsonTemplate(instance.toJSON());
  }
  async install() {
    const defaultStorageConfig = (0, import_storages.getStorageConfig)(this.storageType());
    if (defaultStorageConfig) {
      const Storage = this.db.getCollection("storages");
      if (await Storage.repository.findOne({
        filter: {
          name: defaultStorageConfig.defaults().name
        }
      })) {
        return;
      }
      await Storage.repository.create({
        values: {
          ...defaultStorageConfig.defaults(),
          type: this.storageType(),
          default: true
        }
      });
    }
  }
  async beforeLoad() {
    this.db.registerModels({ FileModel: import_FileModel.FileModel });
    this.db.on("beforeDefineCollection", (options) => {
      if (options.template === "file") {
        options.model = "FileModel";
      }
    });
    this.app.on("afterStart", async () => {
      await this.loadStorages();
    });
  }
  async load() {
    const storagesCollection = this.db.getCollection("storages");
    if (!storagesCollection) {
      throw new Error("Collection storages is not defined after import");
    }
    const Storage = storagesCollection.model;
    Storage.afterSave(async (m, { transaction }) => {
      await this.loadStorages({ transaction });
    });
    Storage.afterDestroy(async (m, { transaction }) => {
      await this.loadStorages({ transaction });
    });
    this.app.acl.registerSnippet({
      name: `pm.file-manager.storages`,
      actions: ["storages:*"]
    });
    this.db.addMigrations({
      namespace: "file-manager",
      directory: (0, import_node_path.resolve)(__dirname, "migrations"),
      context: {
        plugin: this
      }
    });
    (0, import_actions.default)(this);
    this.app.acl.allow("attachments", "upload", "loggedIn");
    this.app.acl.allow("attachments", "create", "loggedIn");
    const defaultStorageName = (0, import_storages.getStorageConfig)(this.storageType()).defaults().name;
    this.app.acl.addFixedParams("storages", "destroy", () => {
      return {
        filter: { "name.$ne": defaultStorageName }
      };
    });
    const ownMerger = () => {
      return {
        filter: {
          createdById: "{{ctx.state.currentUser.id}}"
        }
      };
    };
    this.app.acl.addFixedParams("attachments", "update", ownMerger);
    this.app.acl.addFixedParams("attachments", "create", ownMerger);
    this.app.acl.addFixedParams("attachments", "destroy", ownMerger);
  }
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  storageTypes
});
