import { SaleorAsyncWebhook } from "@saleor/app-sdk/handlers/next";
import {
  OrderCreatedSubscriptionDocument,
  OrderCreatedWebhookPayloadFragment,
} from "@/generated/graphql";
import { saleorApp } from "@/saleor-app";
import { getOrderCreatedEmails } 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 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 } = ctx;
  const order = payload.order;
  
  if (!order) {
    console.error("No order data in webhook payload");
    return res.status(200).end();
  }

  console.log(`Order created: ${order.number} for ${order.userEmail} (lang: ${order.languageCode})`);

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

    // 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 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 email sent to ${adminEmail}: ${adminResult.data?.id || 'failed'}`);
    }
  } catch (error) {
    console.error("Failed to send emails:", error);
  }

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

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