'use strict';
const nodemailer = require('nodemailer');
const { getSetting } = require('../db');

let transporter = null;

function getTransporter() {
  if (transporter) return transporter;
  const host = getSetting('smtp_host', '');
  if (!host) return null;
  transporter = nodemailer.createTransport({
    host,
    port: Number(getSetting('smtp_port', '587')),
    secure: getSetting('smtp_secure', '0') === '1',
    auth: {
      user: getSetting('smtp_user', ''),
      pass: getSetting('smtp_pass', ''),
    },
  });
  return transporter;
}

async function sendMail({ to, subject, html, text }) {
  const t = getTransporter();
  if (!t) {
    console.log(`[mail] SMTP not configured — skipping email to ${to} ("${subject}")`);
    return { skipped: true };
  }
  try {
    const info = await t.sendMail({
      from: `"${getSetting('store_name', 'TOUS CINO')}" <${getSetting('smtp_from', getSetting('email'))}>`,
      to,
      subject,
      html,
      text,
    });
    console.log(`[mail] Sent to ${to}: ${info.messageId}`);
    return { ok: true };
  } catch (err) {
    console.error('[mail] Error sending email:', err.message);
    return { ok: false, error: err.message };
  }
}

function money(n) {
  return 'R ' + Number(n || 0).toLocaleString('en-ZA', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

function orderEmailHtml(order, items) {
  const rows = items
    .map(
      (i) =>
        `<tr><td style="padding:10px;border-bottom:1px solid #eee;">${i.name}${i.size ? ' — size ' + i.size : ''} x ${i.qty}</td>
         <td style="padding:10px;border-bottom:1px solid #eee;text-align:right;">${money(i.price)}</td></tr>`
    )
    .join('');
  const logoUrl = getSetting('site_url', 'http://localhost:3000') + '/public/images/brand/logo.jpeg';
  return `
  <div style="font-family:Arial,sans-serif;max-width:560px;margin:auto;border:1px solid #eee;border-radius:12px;overflow:hidden;">
    <div style="background:#0d0d0d;color:#fff;padding:24px;text-align:center;">
      <img src="${logoUrl}" alt="TOUS CINO" style="width:84px;height:84px;object-fit:cover;border-radius:16px;display:block;margin:0 auto 12px;">
      <div style="font-size:22px;font-weight:800;letter-spacing:2px;">TOUS CINO</div>
      <div style="font-size:11px;letter-spacing:4px;margin-top:4px;">EVERYONE'S SENSE OF FREENESS</div>
    </div>
    <div style="padding:24px;">
      <h2 style="margin-top:0;">Thank you, ${order.name}!</h2>
      <p>Your order <strong>${order.order_number}</strong> has been received.</p>
      <table style="width:100%;border-collapse:collapse;">
        <thead><tr><th align="left">Item</th><th align="right">Price</th></tr></thead>
        <tbody>${rows}</tbody>
      </table>
      <table style="width:100%;margin-top:12px;">
        <tr><td>Subtotal</td><td align="right">${money(order.subtotal)}</td></tr>
        ${order.discount_amount > 0 ? `<tr><td>Discount (${order.coupon_code || ''})</td><td align="right">-${money(order.discount_amount)}</td></tr>` : ''}
        <tr><td>Shipping</td><td align="right">${money(order.shipping_fee)}</td></tr>
        <tr><td style="font-weight:800;">Total</td><td align="right" style="font-weight:800;">${money(order.total)}</td></tr>
      </table>
      <p style="margin-top:20px;color:#666;">Ship to: ${order.address_line1}, ${order.city}, ${order.province} ${order.postal_code}, ${order.country}</p>
      <p>We'll keep you updated on delivery. Questions? Call +27 67 770 0019.</p>
    </div>
  </div>`;
}

function reviewRequestEmailHtml(order) {
  const siteUrl = getSetting('site_url', 'http://localhost:3000');
  const logoUrl = siteUrl + '/public/images/brand/logo.jpeg';
  const reviewUrl = siteUrl + '/?leave-review=1';
  return `
  <div style="font-family:Arial,sans-serif;max-width:560px;margin:auto;border:1px solid #eee;border-radius:12px;overflow:hidden;">
    <div style="background:#0d0d0d;color:#fff;padding:24px;text-align:center;">
      <img src="${logoUrl}" alt="TOUS CINO" style="width:84px;height:84px;object-fit:cover;border-radius:16px;display:block;margin:0 auto 12px;">
      <div style="font-size:22px;font-weight:800;letter-spacing:2px;">TOUS CINO</div>
      <div style="font-size:11px;letter-spacing:4px;margin-top:4px;">EVERYONE'S SENSE OF FREENESS</div>
    </div>
    <div style="padding:24px;">
      <h2 style="margin-top:0;">How was your order, ${order.name}?</h2>
      <p>Your order <strong>${order.order_number}</strong> has been fulfilled — thank you for shopping with us!</p>
      <p>We'd love to know what you think. It only takes a minute and it helps other customers find the right pieces.</p>
      <p style="text-align:center;margin:28px 0;">
        <a href="${reviewUrl}" style="background:#d4af37;color:#14100a;text-decoration:none;font-weight:800;padding:14px 30px;border-radius:40px;letter-spacing:1px;">Leave a review</a>
      </p>
      <p style="color:#666;font-size:13px;">Prefer to stay quiet? No pressure — just ignore this email.</p>
    </div>
  </div>`;
}

module.exports = { sendMail, orderEmailHtml, reviewRequestEmailHtml, money };
