import nodemailer from 'nodemailer';
import { ENV } from '../config/env';

const transporter = nodemailer.createTransport({
  host: ENV.SMTP_HOST,
  port: ENV.SMTP_PORT,
  secure: ENV.SMTP_PORT === 465,
  auth: {
    user: ENV.SMTP_USER,
    pass: ENV.SMTP_PASSWORD,
  },
});

interface SendMailOptions {
  to: string | string[];
  subject: string;
  html: string;
  from?: string;
}

export async function sendMail({ to, subject, html, from }: SendMailOptions) {
  const recipients = Array.isArray(to) ? to.join(', ') : to;

  return transporter.sendMail({
    from: from || `"Ombres & Lumières" <${ENV.EMAIL_FROM}>`,
    to: recipients,
    subject,
    html,
  });
}

/** Send newsletter to a batch of emails (BCC for privacy) */
export async function sendBulkNewsletter(
  emails: string[],
  subject: string,
  html: string,
) {
  // Send in batches of 50 to avoid SMTP limits
  const BATCH_SIZE = 50;
  const results: { sent: number; errors: number } = { sent: 0, errors: 0 };

  for (let i = 0; i < emails.length; i += BATCH_SIZE) {
    const batch = emails.slice(i, i + BATCH_SIZE);
    try {
      await transporter.sendMail({
        from: `"Ombres & Lumières" <newsletter@mafiaz.world>`,
        to: 'newsletter@mafiaz.world', // visible recipient
        bcc: batch, // actual recipients hidden
        subject,
        html: wrapNewsletterTemplate(html, subject),
      });
      results.sent += batch.length;
    } catch (err) {
      console.error(`[MAIL] Batch send error:`, err);
      results.errors += batch.length;
    }
  }

  return results;
}

function wrapNewsletterTemplate(content: string, title: string): string {
  return `
<!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>${title}</title>
  <style>
    body { margin: 0; padding: 0; background: #0a0a0a; color: #e0e0e0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; }
    .container { max-width: 600px; margin: 0 auto; padding: 20px; }
    .header { text-align: center; padding: 30px 0; border-bottom: 2px solid #c41e1e; }
    .header img { max-width: 120px; }
    .header h1 { color: #d4a843; font-size: 20px; margin: 15px 0 0; }
    .content { padding: 30px 0; line-height: 1.7; font-size: 15px; }
    .content h2 { color: #d4a843; }
    .content a { color: #c41e1e; }
    .footer { text-align: center; padding: 20px 0; border-top: 1px solid #222; font-size: 12px; color: #666; }
    .footer a { color: #888; }
    .btn { display: inline-block; padding: 12px 28px; background: linear-gradient(135deg, #8b1a1a, #c41e1e); color: white !important; text-decoration: none; border-radius: 6px; font-weight: bold; }
  </style>
</head>
<body>
  <div class="container">
    <div class="header">
      <h1>Ombres & Lumières</h1>
    </div>
    <div class="content">
      ${content}
    </div>
    <div class="footer">
      <p>Vous recevez cet e-mail car vous êtes inscrit à la newsletter Ombres & Lumières.</p>
      <p><a href="${ENV.FRONTEND_URL}/account">Se désinscrire</a> | <a href="${ENV.FRONTEND_URL}">mafiaz.world</a></p>
      <p>&copy; ${new Date().getFullYear()} Association Permathèque</p>
    </div>
  </div>
</body>
</html>`;
}
