import 'server-only';
import nodemailer, { type Transporter } from 'nodemailer';

// Build an SMTP transport from env vars (works with o2switch, Gmail, Resend SMTP…).
// If SMTP isn't configured, we run in "dev" mode and just log the message.
let cached: Transporter | null | undefined;

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

export const APP_URL = process.env.APP_URL || 'http://localhost:3000';
const FROM = process.env.SMTP_FROM || 'Darsouk <no-reply@darsouk.dz>';

function stripHtml(html: string) {
  return html.replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim();
}

export async function sendEmail(opts: {
  to: string;
  subject: string;
  html: string;
  text?: string;
}): Promise<{ ok: boolean; dev?: boolean }> {
  const t = getTransport();
  const text = opts.text || stripHtml(opts.html);
  if (!t) {
    // Dev fallback: no SMTP configured — log so flows stay testable (e.g. reset links).
    console.log(`\n📧 [email:dev] To: ${opts.to}\n   Subject: ${opts.subject}\n   ${text}\n`);
    return { ok: true, dev: true };
  }
  try {
    await t.sendMail({ from: FROM, to: opts.to, subject: opts.subject, html: opts.html, text });
    return { ok: true };
  } catch (e) {
    console.error('[email] send failed:', e);
    return { ok: false };
  }
}

/** Minimal branded HTML wrapper for transactional emails. */
export function emailLayout(title: string, bodyHtml: string, cta?: { label: string; url: string }): string {
  return `<!doctype html><html><body style="margin:0;background:#FCFBF8;font-family:-apple-system,Segoe UI,Roboto,Arial,sans-serif;color:#1A1714;">
  <div style="max-width:520px;margin:0 auto;padding:32px 24px;">
    <div style="font-weight:800;font-size:22px;color:#F83332;margin-bottom:24px;">Darsouk</div>
    <h1 style="font-size:21px;margin:0 0 12px;">${title}</h1>
    <div style="font-size:15px;line-height:1.6;color:#3a352f;">${bodyHtml}</div>
    ${
      cta
        ? `<a href="${cta.url}" style="display:inline-block;margin-top:22px;background:#F83332;color:#fff;text-decoration:none;font-weight:700;padding:12px 22px;border-radius:10px;">${cta.label}</a>`
        : ''
    }
    <p style="margin-top:28px;font-size:12px;color:#8a8276;">Darsouk — La plateforme des commerces locaux en Algérie.</p>
  </div></body></html>`;
}
