// Copy to `src/subscribers/inventory-level.ts` in your Medusa project.
//
// Event names verified against the installed @medusajs/utils 2.13.6
// InventoryEvents constant (dist/inventory/events.js):
//   "inventory.inventory-level.created" / ".updated" / ".deleted"
//
// These fire on stock quantity changes at a specific location. The payload
// only carries the inventory level's own id, so resolve its location_id and
// inventory_item_id via the Query module before sending (`entity:
// "inventory_level"` is the same query.graph entity name Medusa's own admin
// inventory-item location-levels route uses, verified in
// @medusajs/medusa/dist/api/admin/inventory-items/[id]/location-levels/[location_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<{
      location_id?: string | null;
      inventory_item_id?: string | null;
    }>;
  }>;
};

export async function resolveInventoryLevelWebhookData(
  query: QueryGraph,
  levelId: string,
): Promise<TenderPosWebhookData | null> {
  const { data: levels } = await query.graph({
    entity: "inventory_level",
    fields: ["id", "location_id", "inventory_item_id"],
    filters: { id: levelId },
    // Medusa emits inventory-level.deleted after soft-deleting the level.
    // Include deleted rows so the removal still carries the location/item
    // pair Tender POS needs to reconcile inventory to zero.
    withDeleted: true,
  });

  const level = levels[0];
  if (!level?.location_id || !level.inventory_item_id) return null;
  return {
    resourceType: "inventory_level",
    locationId: level.location_id,
    inventoryItemId: level.inventory_item_id,
  };
}

export default async function tenderPosInventoryLevelHandler({
  event: { name, data },
  container,
}: SubscriberArgs<{ id: string }>) {
  const logger = container.resolve("logger");
  const query = container.resolve("query");
  const webhookData = await resolveInventoryLevelWebhookData(query, data.id);
  if (!webhookData) {
    logger.warn(
      `[tender-pos-webhook] inventory-level event for ${data.id} has no resolvable location/item — skipping`,
    );
    return;
  }

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

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