// Copy to `src/subscribers/product-variant.ts` in your Medusa project.
//
// Event names verified against the installed @medusajs/utils 2.13.6
// ProductVariantWorkflowEvents constant. The event payload only carries the
// variant's own id, so we resolve its parent product id via the Query module
// before sending — pos-api mirrors variant changes through the product they
// belong to (`entity: "variant"` is the same query.graph entity name used by
// Medusa's own admin variant route, verified in
// @medusajs/medusa/dist/api/admin/products/[id]/variants/[variant_id]/route.js).
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 };
    withDeleted: boolean;
  }): Promise<{ data: Array<{ product_id?: string | null }> }>;
};

export async function resolveProductVariantWebhookData(
  query: QueryGraph,
  variantId: string,
): Promise<TenderPosWebhookData | null> {
  const { data: variants } = await query.graph({
    entity: "variant",
    fields: ["id", "product_id"],
    filters: { id: variantId },
    withDeleted: true,
  });

  const productId = variants[0]?.product_id;
  return productId ? { resourceType: "variant", productId } : null;
}

export default async function tenderPosProductVariantHandler({
  event: { name, data },
  container,
}: SubscriberArgs<{ id: string }>) {
  const logger = container.resolve("logger");
  const query = container.resolve("query");
  const webhookData = await resolveProductVariantWebhookData(query, data.id);
  if (!webhookData) {
    logger.warn(
      `[tender-pos-webhook] product-variant event for ${data.id} has no resolvable product_id — skipping`,
    );
    return;
  }

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

export const config: SubscriberConfig = {
  event: [
    "product-variant.created",
    "product-variant.updated",
    "product-variant.deleted",
  ],
  context: { subscriberId: "tender-pos-product-variant" },
};
