var _a, _b;
import { createHash } from "node:crypto";
import { UniqueConstraintViolationException } from "@mikro-orm/core";
import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
import { CarrierShipmentIdempotencyKey } from "../data/entities.js";
const SHIPMENT_IDEMPOTENCY_CONFLICT_MARKER = /* @__PURE__ */ Symbol.for("@open-mercato/ShipmentIdempotencyConflictError");
class ShipmentIdempotencyConflictError extends (_b = Error, _a = SHIPMENT_IDEMPOTENCY_CONFLICT_MARKER, _b) {
  constructor(idempotencyKey) {
    super(`[internal] Shipment idempotency conflict for key "${idempotencyKey}"`);
    this[_a] = true;
    this.name = "ShipmentIdempotencyConflictError";
    this.idempotencyKey = idempotencyKey;
  }
}
function isShipmentIdempotencyConflictError(error) {
  return !!error && typeof error === "object" && error[SHIPMENT_IDEMPOTENCY_CONFLICT_MARKER] === true;
}
function stableSerialize(value) {
  if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null";
  if (Array.isArray(value)) return `[${value.map(stableSerialize).join(",")}]`;
  const entries = Object.entries(value).filter(([, entryValue]) => entryValue !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
  return `{${entries.map(([key, entryValue]) => `${JSON.stringify(key)}:${stableSerialize(entryValue)}`).join(",")}}`;
}
function computeShipmentRequestHash(fingerprint) {
  return createHash("sha256").update(stableSerialize(fingerprint)).digest("hex");
}
async function findShipmentIdempotencyClaim(em, idempotencyKey, providerKey, scope) {
  return findOneWithDecryption(
    em,
    CarrierShipmentIdempotencyKey,
    {
      idempotencyKey,
      providerKey,
      organizationId: scope.organizationId,
      tenantId: scope.tenantId
    },
    void 0,
    scope
  );
}
async function claimShipmentIdempotency(em, idempotencyKey, providerKey, requestHash, scope) {
  const record = em.create(CarrierShipmentIdempotencyKey, {
    idempotencyKey,
    providerKey,
    requestHash,
    shipmentId: null,
    organizationId: scope.organizationId,
    tenantId: scope.tenantId
  });
  try {
    await em.persist(record).flush();
    return record;
  } catch (error) {
    if (error instanceof UniqueConstraintViolationException) return null;
    throw error;
  }
}
async function resolveShipmentIdempotency(em, claim, shipmentId) {
  claim.shipmentId = shipmentId;
  await em.flush();
}
async function releaseShipmentIdempotency(em, idempotencyKey, providerKey, scope) {
  const existing = await findShipmentIdempotencyClaim(em, idempotencyKey, providerKey, scope);
  if (!existing) return;
  await em.remove(existing).flush();
}
export {
  ShipmentIdempotencyConflictError,
  claimShipmentIdempotency,
  computeShipmentRequestHash,
  findShipmentIdempotencyClaim,
  isShipmentIdempotencyConflictError,
  releaseShipmentIdempotency,
  resolveShipmentIdempotency
};
//# sourceMappingURL=shipment-idempotency.js.map
