import type Stripe from "stripe";
import { env } from "@/lib/env";
import { getResendClient, isResendConfigured } from "@/lib/resend";
import { escapeHtml, renderEmailLayout } from "@/lib/email-template";

function formatEuro(cents: number | null | undefined) {
  if (typeof cents !== "number") {
    return "-";
  }
  return new Intl.NumberFormat("fr-FR", { style: "currency", currency: "EUR" }).format(cents / 100);
}

function buildAbandonedCartHtml(items: Stripe.LineItem[]) {
  const itemsHtml = items
    .filter((item) => item.description !== "Livraison")
    .map(
      (item) => `
        <tr>
          <td style="padding:8px 0;border-bottom:1px solid #f1e7d6;font-size:14px;">${escapeHtml(item.description || "Article")} &times; ${item.quantity || 1}</td>
          <td style="padding:8px 0;border-bottom:1px solid #f1e7d6;font-size:14px;text-align:right;">${formatEuro(item.amount_total)}</td>
        </tr>`,
    )
    .join("");

  const cartUrl = `${env.siteUrl}/panier`;

  const bodyHtml = `
    <p style="margin:0 0 16px;font-size:15px;">Bonjour,</p>
    <p style="margin:0 0 20px;font-size:15px;line-height:22px;">
      Vous avez laissé des articles dans votre panier chez Styl'Unique. Ils sont toujours réservés pour vous !
    </p>
    <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="margin-bottom:24px;">
      ${itemsHtml}
    </table>
    <a href="${cartUrl}" style="display:inline-block;background:#7B7168;color:#ffffff;text-decoration:none;padding:12px 22px;border-radius:10px;font-size:14px;font-weight:600;">
      Retrouver mon panier
    </a>
  `;

  return renderEmailLayout({
    title: "Votre panier vous attend",
    preheader: "Vos articles sont toujours dans votre panier.",
    bodyHtml,
  });
}

export async function sendAbandonedCartEmail(session: Stripe.Checkout.Session, lineItems: Stripe.LineItem[]) {
  if (!isResendConfigured()) {
    return;
  }

  const to = session.customer_details?.email || session.customer_email;
  if (!to || lineItems.length === 0) {
    return;
  }

  try {
    await getResendClient().emails.send({
      from: env.resendFromEmail,
      to,
      replyTo: env.resendReplyToEmail || undefined,
      subject: "Vous avez oublié quelque chose dans votre panier",
      html: buildAbandonedCartHtml(lineItems),
    });
  } catch (error) {
    console.error("[abandoned-cart-email] failed to send", error);
  }
}
