/**
 * 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 ai_context_datasource_manager_exports = {};
__export(ai_context_datasource_manager_exports, {
  AIContextDatasourceManager: () => AIContextDatasourceManager
});
module.exports = __toCommonJS(ai_context_datasource_manager_exports);
var import_utils = require("@nocobase/utils");
var import_acl = require("@nocobase/acl");
class AIContextDatasourceManager {
  constructor(plugin) {
    this.plugin = plugin;
  }
  async preview(ctx, options) {
    return await this.innerQuery(ctx, { ...options, filter: options.filter ? (0, import_utils.transformFilter)(options.filter) : null });
  }
  async query(ctx, options) {
    return await this.innerQuery(ctx, { ...options, filter: options.filter });
  }
  provideWorkContextResolveStrategy() {
    return async (ctx, contextItem) => {
      if (!contextItem.content) {
        return "";
      }
      const query = contextItem.content;
      const queryResult = await this.innerQuery(ctx, query);
      return JSON.stringify(queryResult);
    };
  }
  async innerQuery(ctx, options) {
    var _a, _b;
    const { datasource, collectionName } = options;
    const resource = collectionName;
    const action = "list";
    const ds = this.plugin.app.dataSourceManager.get(datasource);
    if (!ds) {
      this.plugin.log.warn(`Datasource ${datasource} not found`);
      return {
        options,
        total: 0,
        records: []
      };
    }
    const collection = ds.collectionManager.getCollection(collectionName);
    if (!collection) {
      this.plugin.log.warn(`Collection ${collectionName} not found`);
      return {
        options,
        total: 0,
        records: []
      };
    }
    if (!((_a = options == null ? void 0 : options.fields) == null ? void 0 : _a.length)) {
      options.fields = collection.getFields().filter((x) => !x.isRelationField()).map((x) => x.options.name);
    }
    const skip = await ds.acl.allowManager.isAllowed(resource, action, ctx);
    if (!skip) {
      const roles = ctx.state.currentRoles || ["anonymous"];
      const can = ds.acl.can({ roles, resource, action, rawResourceName: resource });
      if (!can || typeof can !== "object") {
        return {
          options,
          total: 0,
          records: []
        };
      }
      (0, import_acl.checkFilterParams)(collection, (_b = can.params) == null ? void 0 : _b.filter);
      const parsedParams = can.params ? await (0, import_acl.parseJsonTemplate)(can.params, ctx) : {};
      if (parsedParams.appends && options.fields) {
        for (const queryField of options.fields) {
          if (parsedParams.appends.indexOf(queryField) !== -1) {
            if (!options.appends) {
              options.appends = [];
            }
            options.appends.push(queryField);
            options.fields = options.fields.filter((f) => f !== queryField);
          }
        }
      }
      (0, import_utils.assign)(options, parsedParams, {
        filter: "andMerge",
        fields: "intersect",
        // appends: 'union',
        except: "union",
        whitelist: "intersect",
        blacklist: "intersect",
        // sort: 'overwrite',
        appends: (x, y) => {
          if (!x) {
            return [];
          }
          if (!y) {
            return x;
          }
          return x.filter((i) => y.includes(i.split(".").shift()));
        }
      });
    }
    const { fields, filter, sort, offset, limit } = options;
    const result = await collection.repository.find({ fields, filter, sort, offset: offset ?? 0, limit });
    const total = await collection.repository.count({ fields, filter });
    const records = result.map(
      (x) => fields.map((field) => {
        var _a2;
        const { name, type } = ((_a2 = collection.getField(field)) == null ? void 0 : _a2.options) || {};
        const value = x[field];
        return {
          name,
          type,
          value
        };
      })
    );
    return {
      options,
      total,
      records
    };
  }
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  AIContextDatasourceManager
});
