import { SaleorAsyncWebhook } from "@saleor/app-sdk/handlers/next";
import {
  OrderCancelledSubscriptionDocument,
  OrderCancelledWebhookPayloadFragment,
} from "@/generated/graphql";
import { saleorApp } from "@/saleor-app";

// N8N webhook URL for Order Cancelled
const N8N_WEBHOOK_URL = "https://n8n.nodecrew.me/webhook/saleor-order-cancelled";

export const orderCancelledWebhook = new SaleorAsyncWebhook<OrderCancelledWebhookPayloadFragment>({
  name: "Order Cancelled in Saleor",
  webhookPath: "api/webhooks/order-cancelled",
  event: "ORDER_CANCELLED",
  apl: saleorApp.apl,
  query: OrderCancelledSubscriptionDocument,
});

export default orderCancelledWebhook.createHandler(async (req, res, ctx) => {
  const { payload, event, authData } = ctx;

  console.log(`Order cancelled: ${payload.order?.number} for ${payload.order?.userEmail}`);
  console.log(`Forwarding to N8N: ${N8N_WEBHOOK_URL}`);

  try {
    // Forward to N8N
    const response = await fetch(N8N_WEBHOOK_URL, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "x-saleor-event": "order.cancelled",
      },
      body: JSON.stringify(payload),
    });

    if (!response.ok) {
      console.error(`N8N returned ${response.status}: ${await response.text()}`);
    } else {
      console.log(`Successfully forwarded to N8N: ${response.status}`);
    }
  } catch (error) {
    console.error(`Failed to forward to N8N:`, error);
  }

  return res.status(200).end();
});

export const config = {
  api: {
    bodyParser: false,
  },
};
