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

// N8N webhook URLs - these will forward Saleor events to N8N
const N8N_BASE_URL = "https://n8n.nodecrew.me/webhook";

export const orderConfirmedWebhook = new SaleorAsyncWebhook<OrderConfirmedWebhookPayloadFragment>({
  name: "Order Confirmed - N8N",
  webhookPath: "api/webhooks/order-confirmed",
  event: "ORDER_CONFIRMED",
  apl: saleorApp.apl,
  query: OrderConfirmedSubscriptionDocument,
});

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

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

// Forward webhook payload to N8N
async function forwardToN8N(eventType: string, payload: any) {
  const n8nUrl = `${N8N_BASE_URL}/saleor-${eventType}`;
  
  console.log(`Forwarding ${eventType} to N8N: ${n8nUrl}`);
  
  try {
    const response = await fetch(n8nUrl, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "x-saleor-event": eventType,
      },
      body: JSON.stringify(payload),
    });
    
    if (!response.ok) {
      console.error(`N8N returned ${response.status}: ${await response.text()}`);
      throw new Error(`N8N returned ${response.status}`);
    }
    
    console.log(`Successfully forwarded ${eventType} to N8N`);
    return true;
  } catch (error) {
    console.error(`Failed to forward ${eventType} to N8N:`, error);
    throw error;
  }
}

export const orderConfirmedHandler = orderConfirmedWebhook.createHandler(async (req, res, ctx) => {
  const { payload } = ctx;
  
  console.log(`Order confirmed received: ${payload.order?.id}`);
  
  try {
    await forwardToN8N("order.created", payload);
    return res.status(200).end();
  } catch (error) {
    console.error("Failed to forward order confirmed:", error);
    return res.status(500).end();
  }
});

export const orderFulfilledHandler = orderFulfilledWebhook.createHandler(async (req, res, ctx) => {
  const { payload } = ctx;
  
  console.log(`Order fulfilled received: ${payload.order?.id}`);
  
  try {
    await forwardToN8N("order.fulfilled", payload);
    return res.status(200).end();
  } catch (error) {
    console.error("Failed to forward order fulfilled:", error);
    return res.status(500).end();
  }
});

export const orderCancelledHandler = orderCancelledWebhook.createHandler(async (req, res, ctx) => {
  const { payload } = ctx;
  
  console.log(`Order cancelled received: ${payload.order?.id}`);
  
  try {
    await forwardToN8N("order.cancelled", payload);
    return res.status(200).end();
  } catch (error) {
    console.error("Failed to forward order cancelled:", error);
    return res.status(500).end();
  }
});
