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

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

export const orderFulfilledWebhook = new SaleorAsyncWebhook<OrderFulfilledWebhookPayloadFragment>({
  name: "Order Fulfilled in Saleor",
  webhookPath: "api/webhooks/order-fulfilled",
  event: "ORDER_FULFILLED",
  apl: saleorApp.apl,
  query: OrderFulfilledSubscriptionDocument,
});

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

  console.log(`Order fulfilled: ${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.fulfilled",
      },
      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,
  },
};
