// Copy to `src/subscribers/tender-pos-product-option.ts` in your Medusa
// project.
//
// Event names and `{ id }` payloads verified against the installed
// @medusajs/utils and @medusajs/core-flows 2.13.6 sources. Options and option
// values are mirrored as part of their parent product, so resolve that parent
// (including after a soft delete) and ask Tender POS to refetch the complete
// product graph.
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 resolveProductOptionWebhookData(
  query: QueryGraph,
  optionId: string,
): Promise<TenderPosWebhookData | null> {
  const { data: options } = await query.graph({
    entity: "product_option",
    fields: ["id", "product_id"],
    filters: { id: optionId },
    withDeleted: true,
  });
  const productId = options[0]?.product_id;
  return productId
    ? { resourceType: "product_option", productId }
    : null;
}

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

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

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

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