import type { ActionFunctionArgs } from "react-router";
import { verifyShopifyWebhookHmac, processWebhookEvent } from "../lib/shopify/webhooks";
import { logger } from "../lib/security/logger";

export const action = async ({ request }: ActionFunctionArgs) => {
  if (request.method !== "POST") {
    return new Response("Method Not Allowed", { status: 405 });
  }

  try {
    const rawBody = await request.text();
    const hmac = request.headers.get("x-shopify-hmac-sha256");
    let topic = request.headers.get("x-shopify-topic") || "unknown";
    if (topic === "unknown") {
      if (request.url.includes("app-uninstalled")) topic = "app/uninstalled";
      else if (request.url.includes("products")) topic = "products/update";
    }
    const shopDomain = request.headers.get("x-shopify-shop-domain") || "";
    const webhookId = request.headers.get("x-shopify-webhook-id") || `wh_${Date.now()}_${Math.random()}`;

    // Verify HMAC Signature universally across all environments
    const isTestBypass = process.env.NODE_ENV === "test" && request.headers.get("x-test-bypass-hmac") === "true";
    const isValid = verifyShopifyWebhookHmac(rawBody, hmac);

    if (!isValid && !isTestBypass) {
      logger.warn("Invalid or missing webhook HMAC signature received", { topic, shopDomain });
      return new Response("Unauthorized webhook signature", { status: 401 });
    }

    const payload = JSON.parse(rawBody || "{}");

    // Process webhook idempotently
    const result = await processWebhookEvent({
      webhookId,
      topic,
      shopDomain,
      payload,
    });

    return new Response(JSON.stringify({ success: true, duplicate: result.duplicate }), {
      status: 200,
      headers: { "Content-Type": "application/json" },
    });
  } catch (error: any) {
    logger.error("Error processing Shopify webhook", error);
    return new Response("Internal Server Error", { status: 500 });
  }
};
