// Copy to `src/subscribers/tender-pos-payment.ts` in your Medusa project.
//
// Payment capture/refund changes alter the order mirror's payment rows and
// refunded total. Medusa emits only `{ id: paymentId }`; resolve the order
// through the payment-collection link (the same graph path used by
// @medusajs/core-flows 2.13.6's refund-payments workflow).
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<{
      payment_collection?: { order?: { id?: string | null } | null } | null;
    }>;
  }>;
};

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

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

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

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

export const config: SubscriberConfig = {
  event: ["payment.captured", "payment.refunded"],
  context: { subscriberId: "tender-pos-payment" },
};
