import { registerCommand } from "@open-mercato/shared/lib/commands";
import { FeatureToggle } from "../data/entities.js";
import { processedChangeOverrideStateSchema } from "../data/validators.js";
import { FeatureToggleOverride } from "../data/entities.js";
import { buildChanges } from "@open-mercato/shared/lib/commands/helpers";
import { extractUndoPayload } from "@open-mercato/shared/lib/commands/undo";
import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
import { CrudHttpError } from "@open-mercato/shared/lib/crud/errors";
async function loadOverrideSnapshot(em, toggleId, tenantId) {
  const record = await em.findOne(FeatureToggleOverride, { toggle: toggleId, tenantId });
  if (!record) {
    return {
      id: null,
      toggleId,
      tenantId,
      value: void 0
    };
  }
  return {
    id: record.id ?? null,
    toggleId: record.toggle.id,
    tenantId: record.tenantId,
    value: record.value
  };
}
const changeOverrideStateCommand = {
  id: "feature_toggles.overrides.changeState",
  async prepare(rawInput, ctx) {
    const input = processedChangeOverrideStateSchema.parse(rawInput);
    const em = ctx.container.resolve("em");
    const snapshot = await loadOverrideSnapshot(em, input.toggleId, input.tenantId);
    const result = snapshot ? { before: snapshot } : {};
    return result;
  },
  async execute(rawInput, ctx) {
    const input = processedChangeOverrideStateSchema.parse(rawInput);
    const em = ctx.container.resolve("em");
    const toggle = await em.findOne(FeatureToggle, { id: input.toggleId, deletedAt: null });
    if (!toggle) {
      throw new CrudHttpError(404, { error: "Feature toggle not found" });
    }
    if (!input.isOverride) {
      await em.nativeDelete(FeatureToggleOverride, { toggle: input.toggleId, tenantId: input.tenantId });
      await em.flush();
      const featureTogglesService2 = ctx.container.resolve("featureTogglesService");
      await featureTogglesService2.invalidateIsEnabledCacheByKey(toggle.identifier, input.tenantId);
      return { overrideToggleId: null };
    }
    let override = await em.findOne(FeatureToggleOverride, { toggle: input.toggleId, tenantId: input.tenantId });
    if (override) {
      override.value = input.overrideValue;
      await em.flush();
      const featureTogglesService2 = ctx.container.resolve("featureTogglesService");
      await featureTogglesService2.invalidateIsEnabledCacheByKey(override.toggle.identifier, input.tenantId);
      return { overrideToggleId: override.id };
    }
    override = await em.create(FeatureToggleOverride, {
      toggle,
      tenantId: input.tenantId,
      value: input.overrideValue
    });
    await em.flush();
    const featureTogglesService = ctx.container.resolve("featureTogglesService");
    await featureTogglesService.invalidateIsEnabledCacheByKey(override.toggle.identifier, input.tenantId);
    return { overrideToggleId: override.id };
  },
  buildLog: async ({ snapshots, ctx }) => {
    const before = snapshots.before;
    if (!before) return null;
    const em = ctx.container.resolve("em").fork();
    const after = await loadOverrideSnapshot(em, before.toggleId, before.tenantId);
    if (!after) return null;
    const { translate } = await resolveTranslations();
    return {
      actionLabel: translate("feature_toggles.audit.overrides.changeState", "Change override state"),
      resourceKind: "feature_toggles.overrides",
      resourceId: before.id,
      snapshotBefore: before,
      snapshotAfter: after,
      tenantId: before.tenantId,
      changes: buildChanges(
        before,
        after,
        ["value"]
      ),
      payload: {
        undo: {
          before,
          after
        }
      }
    };
  },
  undo: async ({ logEntry, ctx }) => {
    const payload = extractUndoPayload(logEntry);
    const before = payload?.before;
    if (!before) return;
    const em = ctx.container.resolve("em").fork();
    if (!before.id) {
      await em.nativeDelete(FeatureToggleOverride, { toggle: before.toggleId, tenantId: before.tenantId });
      await em.flush();
      const toggle = await em.findOne(FeatureToggle, { id: before.toggleId });
      if (toggle) {
        const featureTogglesService = ctx.container.resolve("featureTogglesService");
        await featureTogglesService.invalidateIsEnabledCacheByKey(toggle.identifier, before.tenantId);
      }
    } else {
      const existing = await em.findOne(FeatureToggleOverride, { toggle: before.toggleId, tenantId: before.tenantId });
      if (existing) {
        await em.flush();
        const featureTogglesService = ctx.container.resolve("featureTogglesService");
        await featureTogglesService.invalidateIsEnabledCacheByKey(existing.toggle.identifier, existing.tenantId);
      } else {
        const override = em.create(FeatureToggleOverride, {
          toggle: before.toggleId,
          tenantId: before.tenantId,
          value: before.value ?? {}
        });
        await em.flush();
        const featureTogglesService = ctx.container.resolve("featureTogglesService");
        await featureTogglesService.invalidateIsEnabledCacheByKey(override.toggle.identifier, override.tenantId);
      }
    }
  }
};
registerCommand(changeOverrideStateCommand);
//# sourceMappingURL=overrides.js.map
