import { SubscriberArgs, SubscriberConfig } from "@medusajs/framework";
import { ContainerRegistrationKeys } from "@medusajs/framework/utils";
import { getFromAddress, getReplyToAddress, getResendClient, isResendConfigured } from "../lib/resend";
import { escapeHtml, formatEuroCents, renderEmailLayout } from "../lib/email-template";

type OrderItem = {
  title?: string | null;
  quantity?: number | null;
  total?: number | null;
};

type OrderRecord = {
  id: string;
  display_id?: number | string | null;
  email?: string | null;
  total?: number | null;
  shipping_total?: number | null;
  items?: OrderItem[];
  shipping_address?: { first_name?: string | null } | null;
};

async function loadOrder(query: any, orderId: string): Promise<OrderRecord | null> {
  const response = await query.graph({
    entity: "order",
    fields: [
      "id",
      "display_id",
      "email",
      "total",
      "shipping_total",
      "items.title",
      "items.quantity",
      "items.total",
      "shipping_address.first_name",
    ],
    filters: { id: orderId },
  });

  return (response.data?.[0] || null) as OrderRecord | null;
}

function buildOrderConfirmationHtml(order: OrderRecord) {
  const displayNumber = order.display_id || order.id.replace(/^order_/, "").slice(-8).toUpperCase();
  const firstName = order.shipping_address?.first_name?.trim();
  const greeting = firstName ? `Bonjour ${escapeHtml(firstName)},` : "Bonjour,";

  const itemsHtml = (order.items || [])
    .map(
      (item) => `
        <tr>
          <td style="padding:8px 0;border-bottom:1px solid #f1e7d6;font-size:14px;">${escapeHtml(item.title || "Article")} &times; ${item.quantity || 1}</td>
          <td style="padding:8px 0;border-bottom:1px solid #f1e7d6;font-size:14px;text-align:right;">${formatEuroCents(item.total)}</td>
        </tr>`,
    )
    .join("");

  const bodyHtml = `
    <p style="margin:0 0 16px;font-size:15px;">${greeting}</p>
    <p style="margin:0 0 20px;font-size:15px;line-height:22px;">
      Merci pour votre commande ! Voici le récapitulatif de la commande <strong>#${escapeHtml(String(displayNumber))}</strong>.
    </p>
    <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="margin-bottom:16px;">
      ${itemsHtml}
      <tr>
        <td style="padding:10px 0 0;font-size:14px;color:#6e4f4f;">Livraison</td>
        <td style="padding:10px 0 0;font-size:14px;text-align:right;color:#6e4f4f;">${formatEuroCents(order.shipping_total)}</td>
      </tr>
      <tr>
        <td style="padding:6px 0 0;font-size:16px;font-weight:600;">Total</td>
        <td style="padding:6px 0 0;font-size:16px;font-weight:600;text-align:right;">${formatEuroCents(order.total)}</td>
      </tr>
    </table>
    <p style="margin:0;font-size:13px;line-height:20px;color:#6e4f4f;">
      Nous préparons votre commande avec soin. Vous recevrez un email dès son expédition.
    </p>
  `;

  return renderEmailLayout({
    title: `Commande #${displayNumber} confirmée`,
    preheader: `Merci pour votre commande #${displayNumber} chez Styl'Unique.`,
    bodyHtml,
  });
}

export default async function orderConfirmationEmailSubscriber({ event, container }: SubscriberArgs<{ id: string }>) {
  const logger = container.resolve(ContainerRegistrationKeys.LOGGER);

  if (!isResendConfigured()) {
    return;
  }

  const query = container.resolve(ContainerRegistrationKeys.QUERY);
  const orderId = event.data?.id;

  if (!orderId) {
    return;
  }

  try {
    const order = await loadOrder(query, orderId);
    if (!order || !order.email) {
      logger.warn(`[order-confirmation-email] order ${orderId}: missing order or email, skip.`);
      return;
    }

    const displayNumber = order.display_id || order.id.replace(/^order_/, "").slice(-8).toUpperCase();

    await getResendClient().emails.send({
      from: getFromAddress(),
      to: order.email,
      replyTo: getReplyToAddress(),
      subject: `Confirmation de votre commande #${displayNumber}`,
      html: buildOrderConfirmationHtml(order),
    });

    logger.info(`[order-confirmation-email] order ${orderId}: confirmation email sent to ${order.email}.`);
  } catch (error: any) {
    logger.error(`[order-confirmation-email] order ${orderId}: failed to send - ${error?.message || "unknown error"}`);
  }
}

export const config: SubscriberConfig = {
  event: "order.placed",
  context: {
    subscriberId: "order-confirmation-email",
  },
};
