// Copy to `src/subscribers/tender-pos-fulfillment.ts` in your Medusa project.
//
// Shipment and delivery events carry the fulfillment id, not the order id.
// Resolve the order through Medusa's order-fulfillment module link so the
// order's authoritative fulfillment status is refetched.
import type { SubscriberArgs, SubscriberConfig } from "@medusajs/framework";
import {
  sendTenderPosWebhook,
  type TenderPosWebhookData,
} from "../lib/tender-pos-webhook";

type QueryGraph = {
  graph(input: {
    entity: string;
    fields: string[];
    filters: { id: string };
  }): Promise<{ data: Array<{ order?: { id?: string | null } | null }> }>;
};

export async function resolveFulfillmentWebhookData(
  query: QueryGraph,
  fulfillmentId: string,
): Promise<TenderPosWebhookData | null> {
  const { data: fulfillments } = await query.graph({
    entity: "fulfillment",
    fields: ["id", "order.id"],
    filters: { id: fulfillmentId },
  });
  const orderId = fulfillments[0]?.order?.id;
  return orderId ? { resourceType: "fulfillment", orderId } : null;
}

export default async function tenderPosFulfillmentHandler({
  event: { name, data },
  container,
}: SubscriberArgs<{ id: string }>) {
  const logger = container.resolve("logger");
  const query = container.resolve("query");
  const webhookData = await resolveFulfillmentWebhookData(query, data.id);

  if (!webhookData) {
    logger.warn(
      `[tender-pos-webhook] fulfillment event for ${data.id} has no resolvable order — skipping`,
    );
    return;
  }

  await sendTenderPosWebhook({ topic: name, data: webhookData, logger });
}

export const config: SubscriberConfig = {
  event: ["shipment.created", "delivery.created"],
  context: { subscriberId: "tender-pos-fulfillment" },
};
