import { UniqueConstraintViolationException } from "@mikro-orm/core";
import { appVersion } from "@open-mercato/shared/lib/version";
import { parseBooleanToken } from "@open-mercato/shared/lib/boolean";
import { UpgradeActionRun } from "../data/entities.js";
import { actionsUpToVersion, findUpgradeAction } from "../lib/upgrade-actions.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("configs");
function isUpgradeActionsEnabled() {
  return parseBooleanToken(process.env.UPGRADE_ACTIONS_ENABLED ?? "") === true;
}
function getCurrentVersion() {
  return appVersion;
}
async function listPendingUpgradeActions(em, {
  tenantId,
  organizationId,
  version = appVersion
}) {
  if (!isUpgradeActionsEnabled()) return [];
  const definitions = actionsUpToVersion(version);
  if (!definitions.length) return [];
  const versions = Array.from(new Set(definitions.map((definition) => definition.version)));
  const runs = await em.find(UpgradeActionRun, {
    tenantId,
    organizationId,
    version: { $in: versions }
  });
  const completed = new Set(runs.map((run) => `${run.version}::${run.actionId}`));
  return definitions.filter((definition) => !completed.has(`${definition.version}::${definition.id}`));
}
async function executeUpgradeAction(container, {
  actionId,
  tenantId,
  organizationId,
  version = appVersion
}) {
  if (!isUpgradeActionsEnabled()) {
    throw new Error("UPGRADE_ACTIONS_DISABLED");
  }
  const definition = findUpgradeAction(actionId, version);
  if (!definition) {
    throw new Error("UPGRADE_ACTION_NOT_AVAILABLE");
  }
  const em = container.resolve("em");
  const status = await em.transactional(async (tem) => {
    logger.info("Executing upgrade action", {
      component: "upgrade-actions",
      actionId: definition.id,
      version: definition.version,
      requestedVersion: version,
      tenantId,
      organizationId
    });
    const alreadyCompleted = await tem.findOne(UpgradeActionRun, {
      actionId: definition.id,
      version: definition.version,
      tenantId,
      organizationId
    });
    if (alreadyCompleted) return "already_completed";
    await definition.run({ container, em: tem, tenantId, organizationId });
    const record = tem.create(UpgradeActionRun, {
      actionId: definition.id,
      version: definition.version,
      tenantId,
      organizationId
    });
    tem.persist(record);
    await tem.flush();
    logger.info("Upgrade action completed", { component: "upgrade-actions", actionId: definition.id, version, tenantId, organizationId });
    return "completed";
  }).catch((error) => {
    logger.error("Upgrade action failed", { component: "upgrade-actions", actionId, tenantId, organizationId, version, err: error });
    if (error instanceof UniqueConstraintViolationException) {
      return "already_completed";
    }
    throw error;
  });
  return { action: definition, status };
}
export {
  executeUpgradeAction,
  getCurrentVersion,
  isUpgradeActionsEnabled,
  listPendingUpgradeActions
};
//# sourceMappingURL=upgradeActionsService.js.map
