import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
import { CarrierShipment } from "../data/entities.js";
import { emitShippingEvent } from "../events.js";
import { getShippingAdapter } from "../lib/adapter-registry.js";
import { getTerminalShippingEvent, syncShipmentStatus, TERMINAL_SHIPPING_STATUSES } from "../lib/status-sync.js";
import { claimWebhookProcessing, releaseWebhookClaim } from "../lib/webhook-utils.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("shipping_carriers").child({ component: "webhook-processor" });
const metadata = {
  queue: "shipping-carriers-webhook",
  id: "shipping-carriers:webhook-processor",
  concurrency: 5
};
async function handle(job, ctx) {
  try {
    const em = ctx.resolve("em");
    const adapter = getShippingAdapter(job.payload.providerKey);
    if (!adapter) return;
    const shipment = job.payload.shipmentId && job.payload.scope ? await findOneWithDecryption(
      em,
      CarrierShipment,
      {
        id: job.payload.shipmentId,
        organizationId: job.payload.scope.organizationId,
        tenantId: job.payload.scope.tenantId,
        deletedAt: null
      },
      void 0,
      job.payload.scope
    ) : null;
    if (!shipment) return;
    const scope = { organizationId: shipment.organizationId, tenantId: shipment.tenantId };
    const claimed = await claimWebhookProcessing(
      em,
      job.payload.event.idempotencyKey,
      job.payload.providerKey,
      scope,
      job.payload.event.eventType
    );
    if (!claimed) {
      return;
    }
    try {
      const carrierStatus = typeof job.payload.event.data.status === "string" ? job.payload.event.data.status : job.payload.event.eventType;
      const unifiedStatus = adapter.mapStatus(carrierStatus);
      shipment.carrierStatus = carrierStatus;
      shipment.lastWebhookAt = /* @__PURE__ */ new Date();
      const transitionApplied = syncShipmentStatus(shipment, unifiedStatus);
      if (!transitionApplied) return;
      await em.flush();
      const eventPayload = {
        shipmentId: shipment.id,
        providerKey: job.payload.providerKey,
        previousStatus: carrierStatus,
        newStatus: unifiedStatus,
        organizationId: shipment.organizationId,
        tenantId: shipment.tenantId
      };
      await emitShippingEvent("shipping_carriers.shipment.status_changed", eventPayload);
      if (TERMINAL_SHIPPING_STATUSES.has(unifiedStatus)) {
        const terminalEvent = getTerminalShippingEvent(unifiedStatus);
        if (!terminalEvent) return;
        await emitShippingEvent(terminalEvent, eventPayload);
      }
    } catch (error) {
      await releaseWebhookClaim(
        em,
        job.payload.event.idempotencyKey,
        job.payload.providerKey,
        scope
      );
      throw error;
    }
  } catch (error) {
    logger.error("Job processing failed", { providerKey: job.payload.providerKey, shipmentId: job.payload.shipmentId, err: error });
    throw error;
  }
}
export {
  handle as default,
  metadata
};
//# sourceMappingURL=webhook-processor.js.map
