import { SaleorAsyncWebhook } from "@saleor/app-sdk/handlers/next";
import {
  OrderFulfilledSubscriptionDocument,
  OrderFulfilledWebhookPayloadFragment,
} from "@/generated/graphql";
import { saleorApp } from "@/saleor-app";
import { getOrderShippedEmails } from "@/lib/email-templates";
import { Resend } from "resend";

const resend = new Resend(process.env.RESEND_API_KEY);

const ADMIN_EMAILS = ["me@hytham.me", "tamara@hytham.me"];

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

  // Get the first fulfillment with tracking info
  const fulfillment = (order as any).fulfillments?.[0];
  const trackingNumber = fulfillment?.trackingNumber || "";

  console.log(`Order fulfilled: ${order.number} for ${order.userEmail} (lang: ${order.languageCode}, tracking: ${trackingNumber})`);

  try {
    // Get email templates
    const { customerSubject, customerHtml, adminSubject, adminHtml } = getOrderShippedEmails(order, fulfillment);

    // Send customer email
    if (order.userEmail) {
      const customerResult = await resend.emails.send({
        from: "Manoon Oils <support@mail.manoonoils.com>",
        to: order.userEmail,
        subject: customerSubject,
        html: customerHtml,
      });
      console.log(`Customer shipped email sent: ${customerResult.data?.id || 'failed'}`);
    }

    // Send admin emails
    for (const adminEmail of ADMIN_EMAILS) {
      const adminResult = await resend.emails.send({
        from: "Manoon Oils <support@mail.manoonoils.com>",
        to: adminEmail,
        subject: adminSubject,
        html: adminHtml,
      });
      console.log(`Admin shipped email sent to ${adminEmail}: ${adminResult.data?.id || 'failed'}`);
    }
  } catch (error) {
    console.error("Failed to send shipped emails:", error);
  }

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

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