/**
 * SMTP email notifications for form submissions.
 *
 * Used only from Next.js Route Handlers (app/api/*). On every successful
 * form submission the visitor's details are emailed to the site owner
 * (`NOTIFY_EMAIL`), never to the visitor.
 *
 * Credentials live in environment variables and never reach the browser.
 * Email sending is best-effort: if SMTP fails we log the error but never
 * surface it to the visitor or block the submission, so forms keep working.
 */

import nodemailer, { type Transporter } from "nodemailer"

export interface SmtpConfig {
  host: string
  port: number
  secure: boolean
  user: string
  pass: string
  from: string
  notifyEmail: string
}

export function readSmtpConfig(): SmtpConfig | null {
  const user = process.env.SMTP_USER ?? ""
  const pass = process.env.SMTP_PASS ?? ""
  const notifyEmail = process.env.NOTIFY_EMAIL ?? ""
  if (!user || !pass || !notifyEmail) return null
  return {
    host: process.env.SMTP_HOST || "smtp.office365.com",
    port: Number(process.env.SMTP_PORT ?? 587),
    secure: process.env.SMTP_SECURE === "true",
    user,
    pass,
    from: process.env.SMTP_FROM || `MGM Website <${user}>`,
    notifyEmail,
  }
}

let cachedTransport: Transporter | null = null

function getTransport(config: SmtpConfig): Transporter {
  if (cachedTransport) return cachedTransport
  cachedTransport = nodemailer.createTransport({
    host: config.host,
    port: config.port,
    secure: config.secure,
    auth: { user: config.user, pass: config.pass },
  })
  return cachedTransport
}

/** True when SMTP is fully configured and notifications will be attempted. */
export function isSmtpConfigured(): boolean {
  return readSmtpConfig() !== null
}

export interface EmailResult {
  ok: boolean
  message?: string
}

/**
 * Send an HTML notification email to the site owner.
 * Returns { ok: true } when SMTP is unconfigured so callers can treat it as
 * a non-blocking no-op (the Strapi write is the source of truth).
 */
export async function sendNotificationEmail(
  subject: string,
  html: string,
  replyTo?: string,
): Promise<EmailResult> {
  const config = readSmtpConfig()
  if (!config) return { ok: true, message: "SMTP not configured — skipped." }

  try {
    const transport = getTransport(config)
    const info = await transport.sendMail({
      from: config.from,
      to: config.notifyEmail,
      replyTo: replyTo && replyTo.includes("@") ? replyTo : undefined,
      subject,
      html,
    })
    return { ok: true, message: info.messageId }
  } catch (err) {
    return {
      ok: false,
      message: err instanceof Error ? err.message : "SMTP send failed.",
    }
  }
}

/* ----------------------------- HTML helpers ----------------------------- */

function escapeHtml(value: string): string {
  return value
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
}

function row(label: string, value: unknown): string {
  const text = value === null || value === undefined || value === "" ? "—" : escapeHtml(String(value))
  return `
    <tr>
      <td style="padding:8px 12px;color:#6b7280;font-size:13px;border:1px solid #eee;white-space:nowrap;">${escapeHtml(
        label,
      )}</td>
      <td style="padding:8px 12px;color:#111827;font-size:14px;border:1px solid #eee;word-break:break-word;">${text}</td>
    </tr>`
}

function shell(heading: string, rows: string): string {
  return `
  <div style="font-family:Arial,Helvetica,sans-serif;max-width:600px;margin:0 auto;">
    <div style="background:#d20010;padding:16px 20px;border-radius:8px 8px 0 0;">
      <h1 style="margin:0;color:#fff;font-size:18px;font-weight:700;">${escapeHtml(heading)}</h1>
    </div>
    <table style="width:100%;border-collapse:collapse;border:1px solid #eee;border-top:none;">
      ${rows}
    </table>
    <p style="margin:12px 0;color:#9ca3af;font-size:11px;">
      Submitted via the MGM website. This is an automated notification.
    </p>
  </div>`
}

/** Build & send a notification for the Contact form. */
export async function notifyContact(fields: {
  fullName: string
  email: string
  subject: string
  message: string
}): Promise<EmailResult> {
  const html = shell(
    "New Contact Form Submission",
    row("Name", fields.fullName) +
      row("Email", fields.email) +
      row("Subject", fields.subject) +
      row("Message", fields.message),
  )
  return sendNotificationEmail(
    `[Contact] ${fields.subject || "New submission"}`,
    html,
    fields.email,
  )
}

/** Build & send a notification for the Hospitality inquiry form. */
export async function notifyHospitality(fields: {
  fullName: string
  email: string
  enquiryType: string
  message: string
}): Promise<EmailResult> {
  const html = shell(
    "New Hospitality Inquiry",
    row("Name", fields.fullName) +
      row("Email", fields.email) +
      row("Enquiry Type", fields.enquiryType) +
      row("Message", fields.message),
  )
  return sendNotificationEmail(
    `[Hospitality] Inquiry from ${fields.fullName || "a visitor"}`,
    html,
    fields.email,
  )
}

/** Build & send a notification for the Wedding inquiry form. */
export async function notifyWedding(fields: {
  fullName: string
  email: string
  mobile: string
  eventType: string
  eventBudget: string
  eventDate: string | null
  eventTime: string | null
  requirements: string
}): Promise<EmailResult> {
  const html = shell(
    "New Wedding Inquiry",
    row("Name", fields.fullName) +
      row("Email", fields.email) +
      row("Mobile", fields.mobile) +
      row("Event Type", fields.eventType) +
      row("Budget", fields.eventBudget) +
      row("Date", fields.eventDate) +
      row("Time", fields.eventTime) +
      row("Requirements", fields.requirements),
  )
  return sendNotificationEmail(
    `[Wedding] Inquiry from ${fields.fullName || "a visitor"}`,
    html,
    fields.email,
  )
}

/** Build & send a notification for a Newsletter subscription. */
export async function notifyNewsletter(email: string): Promise<EmailResult> {
  const html = shell("New Newsletter Subscriber", row("Email", email))
  return sendNotificationEmail("[Newsletter] New subscriber", html, email)
}
