import { SaleorAsyncWebhook } from "@saleor/app-sdk/handlers/next";
import {
  OrderCancelledSubscriptionDocument,
  OrderCancelledWebhookPayloadFragment,
} from "@/generated/graphql";
import { saleorApp } from "@/saleor-app";
import { sendOrderCancelledEmail, formatPrice } from "@/lib/resend";
import { settingsStore } from "@/lib/settings";

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, baseUrl, authData } = ctx;
  const order = payload.order;
  
  if (!order) {
    console.error("No order data in webhook payload");
    return res.status(200).end();
  }

  const webhookEnabled = await settingsStore.isWebhookEnabled("orderCancelled");
  const sendAdmin = await settingsStore.shouldSendAdminNotification("orderCancelled");
  const sendCustomer = await settingsStore.shouldSendCustomerNotification("orderCancelled");

  console.log(`❌ Order ${order.number} cancelled for customer: ${order.userEmail}`);
  console.log(`📋 Webhook settings - enabled: ${webhookEnabled}, admin: ${sendAdmin}, customer: ${sendCustomer}`);

  if (!webhookEnabled) {
    console.log("⏭️ Webhook disabled, skipping notifications");
    return res.status(200).end();
  }

  const items = ((order as any).lines || []).map((line: any) => ({
    id: line.id,
    name: line.variant?.product?.name || "Unknown Product",
    quantity: line.quantity,
    price: formatPrice(line.totalPrice?.gross?.amount || 0, line.totalPrice?.gross?.currency || "USD"),
  }));

  const orderData = {
    orderId: order.id,
    orderNumber: order.number || "Unknown",
    customerName: (order as any).shippingAddress?.firstName 
      ? `${(order as any).shippingAddress.firstName} ${(order as any).shippingAddress.lastName || ""}`.trim()
      : order.userEmail?.split("@")[0] || "Customer",
    items,
    total: formatPrice((order as any).total?.gross?.amount || 0, (order as any).total?.gross?.currency || "USD"),
  };

  if (sendAdmin) {
    try {
      const adminEmails = process.env.ADMIN_EMAILS?.split(",").map(e => e.trim()).filter(e => e) || [];
      
      if (adminEmails.length > 0) {
        await sendOrderCancelledEmail({
          to: adminEmails,
          orderData,
        });
        console.log(`✅ Admin notification sent for cancelled order ${order.number}`);
      }
    } catch (error) {
      console.error("❌ Failed to send admin email:", error);
    }
  }

  if (sendCustomer) {
    try {
      if (order.userEmail) {
        await sendOrderCancelledEmail({
          to: order.userEmail,
          orderData,
        });
        console.log(`✅ Customer notification sent for cancelled order ${order.number}`);
      }
    } catch (error) {
      console.error("❌ Failed to send customer email:", error);
    }
  } else {
    console.log("⏭️ Customer notification disabled, skipping");
  }

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

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