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

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

export const orderCreatedWebhook = new SaleorAsyncWebhook<OrderCreatedWebhookPayloadFragment>({
  name: "Order Created in Saleor",
  webhookPath: "api/webhooks/order-created",
  event: "ORDER_CREATED",
  apl: saleorApp.apl,
  query: OrderCreatedSubscriptionDocument,
});

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

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