// Copy to `src/subscribers/order.ts` in your Medusa project.
//
// Event names verified against the installed @medusajs/utils 2.13.6
// OrderWorkflowEvents constant (dist/core-flows/events.js). `order.placed`
// is the one that matters most for the POS mirror (fires when a cart is
// completed into an order — verified emitted from
// @medusajs/core-flows/dist/cart/workflows/complete-cart.js); the others
// keep every mirrored order field in sync. The five base lifecycle events
// carry `{ id }`; fulfillment/return/claim/exchange and order-edit events
// carry `{ order_id }`. Normalize both shapes before forwarding.
import type { SubscriberArgs, SubscriberConfig } from "@medusajs/framework";
import { sendTenderPosWebhook } from "../lib/tender-pos-webhook";

type OrderEventData = {
  id?: string;
  order_id?: string;
};

export function orderIdFromEventData(data: OrderEventData): string | null {
  return data.id ?? data.order_id ?? null;
}

export default async function tenderPosOrderHandler({
  event: { name, data },
  container,
}: SubscriberArgs<OrderEventData>) {
  const logger = container.resolve("logger");
  const orderId = orderIdFromEventData(data);
  if (!orderId) {
    logger.warn(
      `[tender-pos-webhook] ${name} event has no id or order_id — skipping`,
    );
    return;
  }

  await sendTenderPosWebhook({
    topic: name,
    data: { resourceType: "order", id: orderId },
    logger,
  });
}

export const config: SubscriberConfig = {
  event: [
    "order.placed",
    "order.updated",
    "order.canceled",
    "order.completed",
    "order.archived",
    "order.fulfillment_created",
    "order.fulfillment_canceled",
    "order.return_requested",
    "order.return_received",
    "order.claim_created",
    "order.exchange_created",
    "order.transfer_requested",
    "order-edit.requested",
    "order-edit.confirmed",
    "order-edit.canceled",
  ],
  context: { subscriberId: "tender-pos-order" },
};
