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

export default async function revalidateStorefrontHandler({
  container,
}: SubscriberArgs) {
  const logger = container.resolve(ContainerRegistrationKeys.LOGGER);

  const storefrontUrl = process.env.STOREFRONT_URL;
  const secret = process.env.REVALIDATE_SECRET;

  if (!storefrontUrl || !secret) {
    logger.warn(
      "STOREFRONT_URL o REVALIDATE_SECRET no configurados; se omite la revalidación del storefront.",
    );
    return;
  }

  try {
    const response = await fetch(`${storefrontUrl}/api/revalidate`, {
      method: "POST",
      headers: { "x-revalidate-secret": secret },
    });

    if (!response.ok) {
      logger.warn(
        `Revalidación del storefront respondió HTTP ${response.status}.`,
      );
    }
  } catch (error) {
    logger.warn(
      `No se pudo revalidar el storefront: ${(error as Error).message}`,
    );
  }
}

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