import "server-only";
import nodemailer from "nodemailer";
import type { Booking, Service } from "@/generated/prisma/client";

function getTransport() {
  const { SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASS } = process.env;
  if (!SMTP_HOST || !SMTP_USER || !SMTP_PASS) {
    return null;
  }
  return nodemailer.createTransport({
    host: SMTP_HOST,
    port: Number(SMTP_PORT) || 587,
    secure: Number(SMTP_PORT) === 465,
    auth: { user: SMTP_USER, pass: SMTP_PASS },
  });
}

function formatMoney(cents: number) {
  return `$${(cents / 100).toFixed(2)}`;
}

function bookingSummaryHtml(booking: Booking, service: Service) {
  return `
    <h2>${service.name}</h2>
    <p><strong>Date:</strong> ${booking.date} at ${booking.startTime}</p>
    <p><strong>Duration:</strong> ${service.durationMinutes} minutes</p>
    <p><strong>Amount paid:</strong> ${formatMoney(booking.amountPaidCents ?? service.priceCents)}</p>
    <p><strong>Customer:</strong> ${booking.customerName} (${booking.customerEmail}, ${booking.customerPhone})</p>
    ${booking.notes ? `<p><strong>Notes:</strong> ${booking.notes}</p>` : ""}
  `;
}

export async function sendBookingConfirmation(
  booking: Booking,
  service: Service,
  notificationEmail: string | null
) {
  const transport = getTransport();
  if (!transport) {
    console.warn(
      "[mail] SMTP is not configured (SMTP_HOST/SMTP_USER/SMTP_PASS env vars) — skipping email send.",
      { bookingId: booking.id }
    );
    return { sent: false, reason: "smtp-not-configured" as const };
  }

  const from = process.env.SMTP_FROM || process.env.SMTP_USER!;
  const recipients: string[] = [booking.customerEmail];
  if (notificationEmail) recipients.push(notificationEmail);

  await transport.sendMail({
    from,
    to: booking.customerEmail,
    bcc: notificationEmail ?? undefined,
    subject: `Booking confirmed: ${service.name} on ${booking.date}`,
    html: `
      <p>Hi ${booking.customerName},</p>
      <p>Your appointment is confirmed. Here are the details:</p>
      ${bookingSummaryHtml(booking, service)}
      <p>We look forward to seeing you!</p>
    `,
  });

  return { sent: true as const };
}
