/**
 * 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 crud_tool_exports = {};
__export(crud_tool_exports, {
  createCrudTools: () => createCrudTools
});
module.exports = __toCommonJS(crud_tool_exports);
var import_light_my_request = __toESM(require("light-my-request"));
function normalizeHeaderValue(value) {
  if (Array.isArray(value)) {
    return value[0];
  }
  return value;
}
function buildActionUrl(resource, action, sourceId) {
  if (typeof sourceId === "undefined" || sourceId === null || !resource.includes(".")) {
    return `${resource}:${action}`;
  }
  const [parentResource, childResource] = resource.split(".");
  return `${parentResource}/${encodeURIComponent(String(sourceId))}/${childResource}:${action}`;
}
function buildQueryValue(value) {
  if (typeof value === "undefined") {
    return void 0;
  }
  if (value === null) {
    return null;
  }
  if (Array.isArray(value)) {
    return value;
  }
  if (typeof value === "object") {
    return JSON.stringify(value);
  }
  return value;
}
function buildRequestQuery(args) {
  const query = {
    filterByTk: buildQueryValue(args.filterByTk),
    filter: buildQueryValue(args.filter),
    fields: buildQueryValue(args.fields),
    appends: buildQueryValue(args.appends),
    except: buildQueryValue(args.except),
    sort: buildQueryValue(args.sort),
    page: buildQueryValue(args.page),
    pageSize: buildQueryValue(args.pageSize),
    paginate: buildQueryValue(args.paginate),
    whitelist: buildQueryValue(args.whitelist),
    blacklist: buildQueryValue(args.blacklist),
    updateAssociationValues: buildQueryValue(args.updateAssociationValues),
    forceUpdate: buildQueryValue(args.forceUpdate)
  };
  Object.keys(query).forEach((key) => {
    if (typeof query[key] === "undefined") {
      delete query[key];
    }
  });
  return query;
}
function buildHeaders(args, context) {
  const incomingHeaders = (context == null ? void 0 : context.headers) || {};
  const headers = {};
  const forwardedRole = normalizeHeaderValue(incomingHeaders["x-role"] || incomingHeaders["X-Role"]);
  if (forwardedRole) {
    headers["x-role"] = forwardedRole;
  }
  const forwardedAuthenticator = normalizeHeaderValue(
    incomingHeaders["x-authenticator"] || incomingHeaders["X-Authenticator"]
  );
  if (forwardedAuthenticator) {
    headers["x-authenticator"] = forwardedAuthenticator;
  }
  if (context == null ? void 0 : context.token) {
    headers.authorization = `Bearer ${context.token}`;
  } else {
    const authorization = normalizeHeaderValue(incomingHeaders.authorization || incomingHeaders.Authorization);
    if (authorization) {
      headers.authorization = authorization;
    }
  }
  headers["content-type"] = "application/json";
  if (args.dataSource && args.dataSource !== "main") {
    headers["x-data-source"] = args.dataSource;
  }
  if ("timezone" in args && args.timezone) {
    headers["x-timezone"] = args.timezone;
  }
  return headers;
}
function buildQueryPayload(args) {
  const payload = {
    measures: args.measures,
    dimensions: args.dimensions,
    orders: args.orders,
    filter: args.filter,
    having: args.having,
    limit: args.limit,
    offset: args.offset
  };
  Object.keys(payload).forEach((key) => {
    if (typeof payload[key] === "undefined") {
      delete payload[key];
    }
  });
  return payload;
}
function buildCrudPayload(action, args) {
  if ((action === "create" || action === "update") && "values" in args) {
    return args.values;
  }
}
function buildActionQuery(action, args) {
  if (action === "query") {
    return void 0;
  }
  return buildRequestQuery(args);
}
function buildActionPayload(action, args) {
  if (action === "query") {
    return buildQueryPayload(args);
  }
  return buildCrudPayload(action, args);
}
function createSharedCall(options, action, tool) {
  var _a;
  const prefix = ((_a = options.app.resourcer.options) == null ? void 0 : _a.prefix) || "/api";
  return async (args, context) => {
    const typedArgs = args || {};
    const actionPath = buildActionUrl(
      typedArgs.resource,
      action,
      "sourceId" in typedArgs ? typedArgs.sourceId : void 0
    );
    const url = `${prefix.replace(/\/$/, "")}/${actionPath}`;
    const response = await (0, import_light_my_request.default)(options.app.callback(), {
      method: "POST",
      url,
      query: buildActionQuery(action, typedArgs),
      headers: buildHeaders(typedArgs, context),
      payload: buildActionPayload(action, typedArgs)
    });
    const contentType = String(response.headers["content-type"] || "").toLowerCase();
    const body = contentType.includes("application/json") || contentType.includes("+json") ? (() => {
      try {
        return response.json();
      } catch (error) {
        return response.payload;
      }
    })() : response.payload;
    if (response.statusCode >= 400) {
      throw new Error(
        JSON.stringify({
          statusCode: response.statusCode,
          body
        })
      );
    }
    return options.mcpToolsManager.postProcessToolResult(
      {
        ...tool,
        resourceName: typedArgs.resource,
        actionName: action,
        path: `/${actionPath}`,
        method: "POST"
      },
      body,
      {
        args: typedArgs,
        callContext: context,
        response: {
          statusCode: response.statusCode,
          headers: response.headers,
          body
        }
      }
    );
  };
}
function createTool(options, action, name, description, inputSchema) {
  const tool = {
    name,
    description,
    inputSchema
  };
  tool.call = createSharedCall(options, action, tool);
  return tool;
}
function createBaseResourceSchema(resourceDescription) {
  return {
    type: "object",
    additionalProperties: false,
    required: ["resource"],
    properties: {
      dataSource: {
        type: "string",
        description: "Data source key. Defaults to main."
      },
      resource: {
        type: "string",
        description: resourceDescription
      }
    }
  };
}
const resourceSchemaDescription = "Resource name, such as users, orders, or association resources like users.roles and posts.comments.";
function createListToolSchema() {
  const base = createBaseResourceSchema(resourceSchemaDescription);
  return {
    ...base,
    properties: {
      ...base.properties,
      sourceId: {
        anyOf: [{ type: "string" }, { type: "number" }],
        description: "Source record ID for association resources like posts.comments."
      },
      filter: {
        type: "object",
        description: "Filter object for list.",
        additionalProperties: true
      },
      fields: {
        type: "array",
        items: { type: "string" },
        description: "Fields to query."
      },
      appends: {
        type: "array",
        items: { type: "string" },
        description: "Association or appended fields to include."
      },
      except: {
        type: "array",
        items: { type: "string" },
        description: "Fields to exclude from the result."
      },
      sort: {
        type: "array",
        items: { type: "string" },
        description: 'Sort fields, such as ["-createdAt"].'
      },
      page: {
        type: "number",
        description: "Page number for list action."
      },
      pageSize: {
        type: "number",
        description: "Page size for list action."
      },
      paginate: {
        type: "boolean",
        description: "Whether to use pagination for list action."
      }
    }
  };
}
function createGetToolSchema() {
  const base = createBaseResourceSchema(resourceSchemaDescription);
  return {
    ...base,
    properties: {
      ...base.properties,
      sourceId: {
        anyOf: [{ type: "string" }, { type: "number" }],
        description: "Source record ID for association resources like posts.comments."
      },
      filterByTk: {
        anyOf: [
          { type: "string" },
          { type: "number" },
          {
            type: "array",
            items: {
              anyOf: [{ type: "string" }, { type: "number" }]
            }
          }
        ],
        description: "Primary key value used by get."
      },
      fields: {
        type: "array",
        items: { type: "string" },
        description: "Fields to query."
      },
      appends: {
        type: "array",
        items: { type: "string" },
        description: "Association or appended fields to include."
      },
      except: {
        type: "array",
        items: { type: "string" },
        description: "Fields to exclude from the result."
      }
    }
  };
}
function createCreateToolSchema() {
  const base = createBaseResourceSchema(resourceSchemaDescription);
  return {
    ...base,
    required: [...base.required, "values"],
    properties: {
      ...base.properties,
      sourceId: {
        anyOf: [{ type: "string" }, { type: "number" }],
        description: "Source record ID for association resources like posts.comments."
      },
      values: {
        type: "object",
        description: "Record values used by create.",
        additionalProperties: true
      },
      whitelist: {
        type: "array",
        items: { type: "string" },
        description: "Fields allowed to be written."
      },
      blacklist: {
        type: "array",
        items: { type: "string" },
        description: "Fields forbidden to be written."
      }
    }
  };
}
function createUpdateToolSchema() {
  const base = createBaseResourceSchema(resourceSchemaDescription);
  return {
    ...base,
    required: [...base.required, "values"],
    properties: {
      ...base.properties,
      sourceId: {
        anyOf: [{ type: "string" }, { type: "number" }],
        description: "Source record ID for association resources like posts.comments."
      },
      filterByTk: {
        anyOf: [
          { type: "string" },
          { type: "number" },
          {
            type: "array",
            items: {
              anyOf: [{ type: "string" }, { type: "number" }]
            }
          }
        ],
        description: "Primary key value used by update."
      },
      filter: {
        type: "object",
        description: "Filter object for update.",
        additionalProperties: true
      },
      values: {
        type: "object",
        description: "Record values used by update.",
        additionalProperties: true
      },
      whitelist: {
        type: "array",
        items: { type: "string" },
        description: "Fields allowed to be written."
      },
      blacklist: {
        type: "array",
        items: { type: "string" },
        description: "Fields forbidden to be written."
      },
      updateAssociationValues: {
        type: "array",
        items: { type: "string" },
        description: "Association fields that should be updated together."
      },
      forceUpdate: {
        type: "boolean",
        description: "Whether update should force writing unchanged values."
      }
    }
  };
}
function createDestroyToolSchema() {
  const base = createBaseResourceSchema(resourceSchemaDescription);
  return {
    ...base,
    properties: {
      ...base.properties,
      sourceId: {
        anyOf: [{ type: "string" }, { type: "number" }],
        description: "Source record ID for association resources like posts.comments."
      },
      filterByTk: {
        anyOf: [
          { type: "string" },
          { type: "number" },
          {
            type: "array",
            items: {
              anyOf: [{ type: "string" }, { type: "number" }]
            }
          }
        ],
        description: "Primary key value used by destroy."
      },
      filter: {
        type: "object",
        description: "Filter object for destroy.",
        additionalProperties: true
      }
    }
  };
}
function createQueryToolSchema() {
  const queryFieldSchema = {
    anyOf: [
      { type: "string" },
      {
        type: "array",
        items: { type: "string" },
        minItems: 1
      }
    ]
  };
  const queryMeasureSchema = {
    type: "object",
    additionalProperties: true,
    required: ["field"],
    properties: {
      field: queryFieldSchema,
      type: {
        type: "string",
        description: "Optional field type hint."
      },
      aggregation: {
        type: "string",
        description: "Aggregation function, such as count, sum, avg, max, or min."
      },
      alias: {
        type: "string",
        description: "Output field alias."
      },
      distinct: {
        type: "boolean",
        description: "Whether to apply distinct before aggregation."
      }
    }
  };
  const queryDimensionSchema = {
    type: "object",
    additionalProperties: true,
    required: ["field"],
    properties: {
      field: queryFieldSchema,
      type: {
        type: "string",
        description: "Optional field type hint."
      },
      alias: {
        type: "string",
        description: "Output field alias."
      },
      format: {
        type: "string",
        description: "Optional output format, usually for date and time dimensions."
      },
      options: {
        type: "object",
        description: "Additional formatter options.",
        additionalProperties: true
      }
    }
  };
  const queryOrderSchema = {
    type: "object",
    additionalProperties: true,
    required: ["field"],
    properties: {
      field: queryFieldSchema,
      alias: {
        type: "string",
        description: "Alias to sort by when the selected field is projected with an alias."
      },
      order: {
        type: "string",
        enum: ["asc", "desc"],
        description: "Sort direction."
      },
      nulls: {
        type: "string",
        enum: ["default", "first", "last"],
        description: "Null value ordering."
      }
    }
  };
  return {
    type: "object",
    additionalProperties: false,
    required: ["resource"],
    properties: {
      dataSource: {
        type: "string",
        description: "Data source key. Defaults to main."
      },
      resource: {
        type: "string",
        description: "Collection resource name, such as users or orders."
      },
      measures: {
        type: "array",
        description: "Measure definitions for query aggregation.",
        items: queryMeasureSchema
      },
      dimensions: {
        type: "array",
        description: "Dimension definitions for query aggregation.",
        items: queryDimensionSchema
      },
      orders: {
        type: "array",
        description: "Order definitions for query aggregation.",
        items: queryOrderSchema
      },
      filter: {
        type: "object",
        description: "Filter object for query.",
        additionalProperties: true
      },
      having: {
        type: "object",
        description: "Having object for grouped query.",
        additionalProperties: true
      },
      limit: {
        type: "number",
        description: "Limit for query result rows."
      },
      offset: {
        type: "number",
        description: "Offset for query result rows."
      },
      timezone: {
        type: "string",
        description: "Optional timezone for query formatting."
      }
    }
  };
}
function createCrudTools(options) {
  const listSchema = createListToolSchema();
  const getSchema = createGetToolSchema();
  const createSchema = createCreateToolSchema();
  const updateSchema = createUpdateToolSchema();
  const destroySchema = createDestroyToolSchema();
  const querySchema = createQueryToolSchema();
  return [
    createTool(options, "list", "resource_list", "List records from a collection.", listSchema),
    createTool(options, "get", "resource_get", "Get a record from a collection.", getSchema),
    createTool(options, "create", "resource_create", "Create a record in a collection.", createSchema),
    createTool(options, "update", "resource_update", "Update records in a collection.", updateSchema),
    createTool(options, "destroy", "resource_destroy", "Delete records from a collection.", destroySchema),
    createTool(options, "query", "resource_query", "Run an aggregate query on a collection.", querySchema)
  ];
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  createCrudTools
});
