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 UpdateInstruction_exports = {};
__export(UpdateInstruction_exports, {
  UpdateInstruction: () => UpdateInstruction,
  default: () => UpdateInstruction_default
});
module.exports = __toCommonJS(UpdateInstruction_exports);
var import_server = require("@tego/server");
var import_axios = __toESM(require("axios"));
var import_form_data = __toESM(require("form-data"));
var import_lodash = __toESM(require("lodash"));
var import_mime_types = __toESM(require("mime-types"));
var import__ = require(".");
var import_constants = require("../constants");
var import_utils = require("../utils");
class UpdateInstruction extends import__.Instruction {
  async run(node, input, processor) {
    var _a, _b;
    const { collection, params = {} } = node.config;
    const [dataSourceName, collectionName] = (0, import_server.parseCollectionName)(collection);
    const { repository } = this.workflow.app.dataSourceManager.dataSources.get(dataSourceName).collectionManager.getCollection(collectionName);
    const options = processor.getParsedValue(params, node.id);
    const c = this.workflow.app.dataSourceManager.dataSources.get(dataSourceName).collectionManager.getCollection(collectionName);
    const fields = c.getFields();
    const fieldNames = Object.keys(params.values);
    const includesFields = fields.filter((field) => fieldNames.includes(field.options.name));
    const userId = import_lodash.default.get(processor.getScope(node.id), "$context.user.id", "");
    const token = this.workflow.app.authManager.jwt.sign({ userId });
    const isJSON = (str) => {
      try {
        return JSON.parse(str);
      } catch (e) {
        return false;
      }
    };
    const handleResource = async (resource) => {
      if (typeof resource === "object" && (resource == null ? void 0 : resource.url) && (resource == null ? void 0 : resource.filename)) {
        const {
          id,
          createdAt,
          updatedAt,
          title,
          filename,
          extname,
          size,
          mimetype,
          path,
          meta,
          url,
          createById,
          updatedById,
          storageId
        } = resource || {};
        return {
          id,
          createdAt,
          updatedAt,
          title,
          filename,
          extname,
          size,
          mimetype,
          path,
          meta,
          url,
          createById,
          updatedById,
          storageId
        };
      }
      const parseRes = isJSON(resource);
      const config = {
        method: "get",
        url: resource,
        responseType: "stream"
      };
      const form = new import_form_data.default();
      if (resource.startsWith("data:")) {
        const matches = resource.match(/^data:(.+);base64,(.+)$/);
        if (matches) {
          const contentType = matches[1];
          const base64Data = matches[2];
          const buffer = Buffer.from(base64Data, "base64");
          const ext = import_mime_types.default.extension(contentType);
          const filename = `${(0, import_server.uid)()}.${ext}`;
          form.append("file", buffer, {
            filename,
            contentType
          });
        } else {
          throw new Error("Invalid data URL format");
        }
      } else if (parseRes) {
        const {
          url: resourceUrl,
          params: resourceParams,
          headers: resourceHeaders,
          body: resourceBody,
          filename
        } = parseRes;
        config.url = resourceUrl;
        config.params = resourceParams;
        config.headers = resourceHeaders;
        if (resourceHeaders["content-type"] === "multipart/form-data") {
          const formData = new import_form_data.default();
          Object.entries(resourceBody).forEach(([key, value]) => {
            formData.append(key, value);
          });
          config.data = formData;
        } else {
          config.data = resourceBody;
        }
        const response = await (0, import_axios.default)(config);
        const contentType = response.headers["content-type"];
        const ext = import_mime_types.default.extension(contentType);
        const fullFilename = `${filename || (0, import_server.uid)()}.${ext}`;
        form.append("file", response.data, {
          filename: fullFilename,
          contentType: response.headers["content-type"]
        });
      } else {
        const response = await (0, import_axios.default)(config);
        const contentType = response.headers["content-type"];
        const ext = import_mime_types.default.extension(contentType);
        const filename = `${(0, import_server.uid)()}.${ext}`;
        form.append("file", response.data, {
          filename,
          contentType: response.headers["content-type"]
        });
      }
      const origin = import_server.Gateway.getInstance().runAtLoop;
      const uploadResponse = await (0, import_axios.default)({
        method: "post",
        url: origin + "/api/attachments:create",
        data: form,
        headers: {
          ...form.getHeaders(),
          Authorization: "Bearer " + token
        }
      });
      return uploadResponse.data.data;
    };
    for (const attachmentField of includesFields) {
      if (attachmentField.options.interface === "attachment") {
        let targetField = options.values[attachmentField.options.name];
        if (Array.isArray(targetField)) {
          for (const i in targetField) {
            targetField[i] = await handleResource(targetField[i]);
          }
        } else {
          options.values[attachmentField.options.name] = [await handleResource(targetField)];
        }
      }
    }
    const result = await repository.update({
      ...options,
      context: {
        stack: Array.from(new Set((processor.execution.context.stack ?? []).concat(processor.execution.id))),
        state: (_b = (_a = processor.options) == null ? void 0 : _a.httpContext) == null ? void 0 : _b.state
      },
      transaction: this.workflow.useDataSourceTransaction(dataSourceName, processor.transaction)
    });
    return {
      result: {
        length: (result == null ? void 0 : result.length) ?? result,
        data: (0, import_utils.toJSON)(result) ?? []
      },
      status: import_constants.JOB_STATUS.RESOLVED
    };
  }
}
var UpdateInstruction_default = UpdateInstruction;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  UpdateInstruction
});
