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

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, 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("orderCreated");
  const sendAdmin = await settingsStore.shouldSendAdminNotification("orderCreated");
  const sendCustomer = await settingsStore.shouldSendCustomerNotification("orderCreated");

  console.log(`🎉 Order #${order.number} created for customer: ${order.userEmail} (${order.languageCode || "EN"})`);
  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",
    customerEmail: order.userEmail || "",
    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"),
    shippingAddress: (order as any).shippingAddress 
      ? `${(order as any).shippingAddress.firstName || ""} ${(order as any).shippingAddress.lastName || ""}\n${(order as any).shippingAddress.streetAddress1 || ""}\n${(order as any).shippingAddress.postalCode || ""} ${(order as any).shippingAddress.city || ""}\n${(order as any).shippingAddress.country?.country || ""}${(order as any).shippingAddress.phone ? `\nPhone: ${(order as any).shippingAddress.phone}` : ""}`
      : undefined,
    billingAddress: (order as any).billingAddress
      ? `${(order as any).billingAddress.firstName || ""} ${(order as any).billingAddress.lastName || ""}\n${(order as any).billingAddress.streetAddress1 || ""}\n${(order as any).billingAddress.postalCode || ""} ${(order as any).billingAddress.city || ""}\n${(order as any).billingAddress.country?.country || ""}${(order as any).billingAddress.phone ? `\nPhone: ${(order as any).billingAddress.phone}` : ""}`
      : undefined,
    phone: (order as any).shippingAddress?.phone,
  };

  if (sendAdmin) {
    try {
      const adminEmails = process.env.ADMIN_EMAILS?.split(",").map(e => e.trim()).filter(e => e) || [];
      
      if (adminEmails.length > 0) {
        await sendOrderConfirmationEmail({
          to: adminEmails,
          orderData,
          isAdmin: true,
        });
        console.log(`✅ Admin notification sent for order #${order.number} to: ${adminEmails.join(", ")}`);
      } else {
        console.log("⚠️ No admin emails configured, skipping admin notification");
      }
    } catch (error) {
      console.error("❌ Failed to send admin email:", error);
    }
  } else {
    console.log("⏭️ Admin notification disabled, skipping");
  }

  if (sendCustomer) {
    try {
      if (order.userEmail) {
        await sendOrderConfirmationEmail({
          to: order.userEmail,
          orderData,
          isAdmin: false,
        });
        console.log(`✅ Customer confirmation sent for order #${order.number} to: ${order.userEmail}`);
      } else {
        console.log("⚠️ No customer email found, skipping customer notification");
      }
    } 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,
  },
};