var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : Symbol.for("Symbol." + name);
var __typeError = (msg) => {
  throw TypeError(msg);
};
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
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 __decoratorStart = (base) => [, , , __create((base == null ? void 0 : base[__knownSymbol("metadata")]) ?? null)];
var __decoratorStrings = ["class", "method", "getter", "setter", "accessor", "field", "value", "get", "set"];
var __expectFn = (fn) => fn !== void 0 && typeof fn !== "function" ? __typeError("Function expected") : fn;
var __decoratorContext = (kind, name, done, metadata, fns) => ({ kind: __decoratorStrings[kind], name, metadata, addInitializer: (fn) => done._ ? __typeError("Already initialized") : fns.push(__expectFn(fn || null)) });
var __decoratorMetadata = (array, target) => __defNormalProp(target, __knownSymbol("metadata"), array[3]);
var __runInitializers = (array, flags, self, value) => {
  for (var i = 0, fns = array[flags >> 1], n = fns && fns.length; i < n; i++) flags & 1 ? fns[i].call(self) : value = fns[i].call(self, value);
  return value;
};
var __decorateElement = (array, flags, name, decorators, target, extra) => {
  var fn, it, done, ctx, access, k = flags & 7, s = !!(flags & 8), p = !!(flags & 16);
  var j = k > 3 ? array.length + 1 : k ? s ? 1 : 2 : 0, key = __decoratorStrings[k + 5];
  var initializers = k > 3 && (array[j - 1] = []), extraInitializers = array[j] || (array[j] = []);
  var desc = k && (!p && !s && (target = target.prototype), k < 5 && (k > 3 || !p) && __getOwnPropDesc(k < 4 ? target : { get [name]() {
    return __privateGet(this, extra);
  }, set [name](x) {
    return __privateSet(this, extra, x);
  } }, name));
  k ? p && k < 4 && __name(extra, (k > 2 ? "set " : k > 1 ? "get " : "") + name) : __name(target, name);
  for (var i = decorators.length - 1; i >= 0; i--) {
    ctx = __decoratorContext(k, name, done = {}, array[3], extraInitializers);
    if (k) {
      ctx.static = s, ctx.private = p, access = ctx.access = { has: p ? (x) => __privateIn(target, x) : (x) => name in x };
      if (k ^ 3) access.get = p ? (x) => (k ^ 1 ? __privateGet : __privateMethod)(x, target, k ^ 4 ? extra : desc.get) : (x) => x[name];
      if (k > 2) access.set = p ? (x, y) => __privateSet(x, target, y, k ^ 4 ? extra : desc.set) : (x, y) => x[name] = y;
    }
    it = (0, decorators[i])(k ? k < 4 ? p ? extra : desc[key] : k > 4 ? void 0 : { get: desc.get, set: desc.set } : target, ctx), done._ = 1;
    if (k ^ 4 || it === void 0) __expectFn(it) && (k > 4 ? initializers.unshift(it) : k ? p ? extra = it : desc[key] = it : target = it);
    else if (typeof it !== "object" || it === null) __typeError("Object expected");
    else __expectFn(fn = it.get) && (desc.get = fn), __expectFn(fn = it.set) && (desc.set = fn), __expectFn(fn = it.init) && initializers.unshift(fn);
  }
  return k || __decoratorMetadata(array, target), desc && __defProp(target, name, desc), p ? k ^ 4 ? extra : desc : target;
};
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
var __privateIn = (member, obj) => Object(obj) !== obj ? __typeError('Cannot use the "in" operator on this value') : member.has(obj);
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
var cloud_libraries_controller_exports = {};
__export(cloud_libraries_controller_exports, {
  CloudLibrariesController: () => CloudLibrariesController
});
module.exports = __toCommonJS(cloud_libraries_controller_exports);
var import_server = require("@tego/server");
var import_cloud_compiler = require("../services/cloud-compiler");
var import_remote_code_fetcher = require("../services/remote-code-fetcher");
var _syncRemoteCode_dec, _destroy_dec, _publish_dec, _update_dec, _logger_dec, _remoteCodeFetcher_dec, _compiler_dec, _CloudLibrariesController_decorators, _init;
_CloudLibrariesController_decorators = [(0, import_server.Controller)("cloudLibraries")], _compiler_dec = [(0, import_server.Inject)(() => import_cloud_compiler.CloudCompiler)], _remoteCodeFetcher_dec = [(0, import_server.Inject)(() => import_remote_code_fetcher.RemoteCodeFetcher)], _logger_dec = [(0, import_server.InjectLog)()], _update_dec = [(0, import_server.Action)("update")], _publish_dec = [(0, import_server.Action)("publish")], _destroy_dec = [(0, import_server.Action)("destroy")], _syncRemoteCode_dec = [(0, import_server.Action)("syncRemoteCode")];
class CloudLibrariesController {
  constructor() {
    __runInitializers(_init, 5, this);
    this.compiler = __runInitializers(_init, 8, this), __runInitializers(_init, 11, this);
    this.remoteCodeFetcher = __runInitializers(_init, 12, this), __runInitializers(_init, 15, this);
    this.logger = __runInitializers(_init, 16, this), __runInitializers(_init, 19, this);
  }
  async update(ctx, next) {
    const {
      name,
      code,
      codeSource = "local",
      codeType,
      codeUrl,
      codeBranch = "main",
      codePath,
      module: module2,
      isClient,
      isServer,
      serverPlugin,
      clientPlugin,
      enabled,
      component
    } = ctx.action.params.values;
    let codeToCompile = code;
    if (codeSource === "remote" && codeUrl && codeType && code) {
      codeToCompile = code;
    }
    if (codeToCompile) {
      const clientCode = this.compiler.toAmd(codeToCompile);
      const serverCode = this.compiler.toCjs(codeToCompile);
      const { db } = ctx;
      const repo = db.getRepository("effectLibraries");
      repo.updateOrCreate({
        filterKeys: ["module"],
        values: {
          name,
          module: module2,
          enabled,
          server: serverCode,
          client: clientCode,
          isClient,
          isServer,
          serverPlugin,
          clientPlugin,
          component
        }
      });
    }
    await import_server.actions.update(ctx, next);
  }
  async publish(ctx, next) {
    const {
      code,
      codeSource = "local",
      codeType,
      codeUrl,
      codeBranch = "main",
      codePath,
      module: module2,
      isClient,
      isServer,
      serverPlugin,
      clientPlugin,
      enabled,
      component
    } = ctx.action.params.values;
    let codeToCompile = code;
    if (codeSource === "remote" && codeUrl && codeType && code) {
      codeToCompile = code;
    }
    if (codeToCompile) {
      const clientCode = this.compiler.toAmd(codeToCompile);
      const serverCode = this.compiler.toCjs(codeToCompile);
      const { db } = ctx;
      const repo = db.getRepository("effectLibraries");
      repo.updateOrCreate({
        filterKeys: ["module"],
        values: {
          module: module2,
          enabled,
          server: serverCode,
          client: clientCode,
          isClient,
          isServer,
          serverPlugin,
          clientPlugin,
          component
        }
      });
    }
    await import_server.actions.update(ctx, next);
  }
  async destroy(ctx, next) {
    const { filterByTk } = ctx.action.params;
    const cloudRepo = ctx.db.getRepository("cloudLibraries");
    const effectRepo = ctx.db.getRepository("effectLibraries");
    try {
      await ctx.db.sequelize.transaction(async (transaction) => {
        const cloudComponent = await cloudRepo.findOne({
          filterByTk,
          transaction
        });
        if (!cloudComponent) {
          throw new Error(`Cloud component with id ${filterByTk} not found`);
        }
        await effectRepo.destroy({
          filter: {
            name: cloudComponent.name,
            module: cloudComponent.module
          },
          transaction
        });
        await cloudRepo.destroy({
          filterByTk,
          transaction
        });
      });
    } catch (error) {
      this.logger.error("Error deleting cloud component:", {
        error: error instanceof Error ? error.message : String(error),
        stack: error instanceof Error ? error.stack : void 0,
        filterByTk
      });
      throw error;
    }
  }
  async syncRemoteCode(ctx, next) {
    const params = ctx.action.params.values || ctx.action.params || {};
    const {
      codeUrl,
      codeType,
      codeBranch = "main",
      codePath,
      codeAuthType,
      codeAuthToken,
      codeAuthUsername,
      recordId
    } = params;
    if (!codeUrl || !codeType) {
      this.logger.warn("syncRemoteCode: Missing required parameters", { params });
      ctx.throw(400, "codeUrl and codeType are required");
    }
    try {
      this.logger.info(
        `Syncing remote code (force refresh): ${codeUrl} (type: ${codeType}, branch: ${codeBranch || "main"})`
      );
      const code = await this.remoteCodeFetcher.fetchCode(
        codeUrl,
        codeType,
        codeBranch,
        codePath,
        codeAuthType,
        codeAuthToken,
        codeAuthUsername
      );
      ctx.body = {
        code
      };
      if (recordId && code) {
        try {
          const repository = ctx.db.getRepository("cloudLibraries");
          await repository.update({
            filterByTk: recordId,
            values: {
              lastSyncTime: /* @__PURE__ */ new Date()
            }
          });
        } catch (error) {
          this.logger.warn("Failed to update lastSyncTime", {
            error: error instanceof Error ? error.message : String(error),
            recordId
          });
        }
      }
      await next();
    } catch (error) {
      if (ctx.status && ctx.status !== 200) {
        throw error;
      }
      this.logger.error("Failed to sync remote code", {
        error: error instanceof Error ? error.message : String(error),
        stack: error instanceof Error ? error.stack : void 0,
        params
      });
      ctx.throw(500, `Failed to fetch remote code: ${error instanceof Error ? error.message : String(error)}`);
    }
  }
}
_init = __decoratorStart(null);
__decorateElement(_init, 1, "update", _update_dec, CloudLibrariesController);
__decorateElement(_init, 1, "publish", _publish_dec, CloudLibrariesController);
__decorateElement(_init, 1, "destroy", _destroy_dec, CloudLibrariesController);
__decorateElement(_init, 1, "syncRemoteCode", _syncRemoteCode_dec, CloudLibrariesController);
__decorateElement(_init, 5, "compiler", _compiler_dec, CloudLibrariesController);
__decorateElement(_init, 5, "remoteCodeFetcher", _remoteCodeFetcher_dec, CloudLibrariesController);
__decorateElement(_init, 5, "logger", _logger_dec, CloudLibrariesController);
CloudLibrariesController = __decorateElement(_init, 0, "CloudLibrariesController", _CloudLibrariesController_decorators, CloudLibrariesController);
__runInitializers(_init, 1, CloudLibrariesController);
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  CloudLibrariesController
});
