import { authenticate } from "../shopify.server";
import { syncDraftOrderGifts } from "../utils.draft-order-gifts.server";

/**
 * draft_orders/create and draft_orders/update.
 *
 * Checkout extensions cannot change lines on a Draft Order checkout, so gift
 * lines are kept in sync on the Draft Order itself.
 */
export const action = async ({ request }) => {
  const { shop, admin, payload, topic } = await authenticate.webhook(request);

  // No offline session (e.g. the app was uninstalled): nothing to do.
  if (!admin) return new Response();

  const draftOrderId = payload?.admin_graphql_api_id;

  if (!draftOrderId || String(payload?.status).toLowerCase() === "completed") {
    return new Response();
  }

  try {
    const result = await syncDraftOrderGifts({
      shop,
      admin,
      draftOrderId,
      topic,
    });

    console.log(`[draft-order-gift-sync] ${topic} ${draftOrderId}`, result);
  } catch (error) {
    // Logged, then acknowledged: a failing rule must not make Shopify retry
    // the webhook in a loop. The next update to the Draft Order re-syncs it.
    console.error(`[draft-order-gift-sync] ${topic} ${draftOrderId}`, error);
  }

  return new Response();
};
