/**
 * 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 __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var foreign_data_collection_exports = {};
__export(foreign_data_collection_exports, {
  ForeignDataCollection: () => ForeignDataCollection
});
module.exports = __toCommonJS(foreign_data_collection_exports);
var import_database = require("@nocobase/database");
var import_remote_local_bridge = require("./bridges/remote-local-bridge");
class ForeignDataCollection extends import_database.Collection {
  constructor(options, context) {
    if (!options.autoGenId) {
      options.autoGenId = false;
    }
    if (!options.timestamps) {
      options.timestamps = false;
    }
    options.underscored = false;
    super(options, context);
  }
  static registerOptions(plugin) {
    return {
      condition(options) {
        return options.remoteServerName && options.remoteTableInfo;
      },
      async onDump() {
        return;
      },
      async onSync(model, options) {
        const transaction = options == null ? void 0 : options.transaction;
        const { remoteServerName, remoteTableInfo } = model.collection.options;
        const remoteServerInstance = await model.database.getRepository("databaseServers").findOne({
          filterByTk: remoteServerName,
          transaction
        });
        if (!remoteServerInstance) {
          throw new Error(`remoteServer ${remoteServerName} not found`);
        }
        remoteServerInstance.setApp(plugin.app);
        await remoteServerInstance.createServer({
          transaction
        });
        const remoteLocalBridge = import_remote_local_bridge.RemoteLocalBridgeFactory.createBridge({
          remoteDatabase: remoteServerInstance.getRemoteDatabaseInstance(),
          localDatabase: model.database
        });
        await remoteLocalBridge.createTable({
          remoteServerName,
          remoteTableDefinition: await remoteServerInstance.showTableDefinition(remoteTableInfo),
          remoteTableInfo,
          localModel: model,
          transaction
        });
      }
    };
  }
  async removeFieldFromDb(name, options) {
    const field = this.getField(name);
    if (field) {
      field.remove();
    }
  }
  async removeFromDb(options) {
    const transaction = options == null ? void 0 : options.transaction;
    if (this.db.inDialect("postgres")) {
      let sql = `DROP FOREIGN TABLE IF EXISTS ${this.getTableNameWithSchemaAsString()}`;
      if (options == null ? void 0 : options.cascade) {
        sql += " CASCADE";
      }
      await this.db.sequelize.query(sql, {
        transaction
      });
      return this.remove();
    } else {
      await super.removeFromDb(options);
    }
  }
  bindFieldEventListener() {
    super.bindFieldEventListener();
    this.on("field.afterAdd", (field) => {
      const interfaceOption = field.options.interface;
      if (interfaceOption === "updatedAt") {
        this.model._timestampAttributes.createdAt = field.name;
      }
      if (interfaceOption === "createdAt") {
        this.model._timestampAttributes.updatedAt = field.name;
      }
    });
  }
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  ForeignDataCollection
});
