import type { ActionFunctionArgs } from "react-router";
import { authenticate } from "../shopify.server";
import { reserveWebhook } from "../services/webhooks/dedupe.server";

// Acknowledged but not yet acted on. Future: invalidate cached invoice
// snapshots when a relevant field on the order changes.
export const action = async ({ request }: ActionFunctionArgs) => {
  const { shop, topic } = await authenticate.webhook(request);
  console.log(`Received ${topic} webhook for ${shop}`);
  // Idempotency against Shopify retries — see webhooks/dedupe.server.ts.
  const reservation = await reserveWebhook(request, shop, topic);
  if (!reservation) return new Response();
  // No side-effect work yet, so the delivery is immediately complete.
  await reservation.commit();
  return new Response();
};
