import type {
  SubscriberArgs,
  SubscriberConfig,
} from "@medusajs/framework"

export default async function productUpdatedHandler({
  event: { data },
  container,
}: SubscriberArgs<{ id: string }>) {
  const logger = container.resolve("logger")
  const storeUrl = process.env.STORE_URL || "http://localhost:8000"
  const secret = process.env.REVALIDATE_SECRET

  if (!secret) {
    logger.warn(
      "[product-updated] REVALIDATE_SECRET not set, skipping revalidation"
    )
    return
  }

  const url = `${storeUrl}/api/revalidate?secret=${secret}&tag=products`

  try {
    const res = await fetch(url, { method: "GET" })
    if (res.ok) {
      logger.info(
        `[product-updated] Cache revalidated for product ${data.id}`
      )
    } else {
      logger.error(
        `[product-updated] Revalidation failed: ${res.status} ${res.statusText}`
      )
    }
  } catch (error) {
    logger.error(
      `[product-updated] Revalidation error: ${error}`
    )
  }
}

export const config: SubscriberConfig = {
  event: ["product.updated", "product.created", "product-variant.updated"],
}
