import nodemailer from 'nodemailer';

let transporter = null;

function getTransporter() {
  if (!process.env.EMAIL_USER || !process.env.EMAIL_PASS) {
    const error = new Error('E-Mail-Versand ist nicht konfiguriert.');
    error.code = 'EMAIL_CONFIG_MISSING';
    throw error;
  }

  if (!transporter) {
    transporter = nodemailer.createTransport({
      service: 'Gmail',
      auth: {
        user: process.env.EMAIL_USER,
        pass: process.env.EMAIL_PASS,
      },
    });
  }

  return transporter;
}

function getDefaultFrom() {
  return process.env.EMAIL_FROM || process.env.EMAIL_USER;
}

async function sendMail(mailOptions) {
  return getTransporter().sendMail({
    from: getDefaultFrom(),
    ...mailOptions,
  });
}
 
const sendActivationEmail = async (email, activationCode) => {
  await sendMail({
    to: email,
    subject: 'Account Activation',
    text: `Activate your account by clicking the following link: ${process.env.BASE_URL}/activate/${activationCode}`,
  });
};

const sendPasswordResetEmail = async (email, resetToken) => {
  const resetLink = `${process.env.BASE_URL}/reset-password/${resetToken}`;
  await sendMail({
    to: email,
    subject: 'Passwort zurücksetzen',
    html: `
      <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto;">
        <h2 style="color: #333;">Passwort zurücksetzen</h2>
        <p>Du hast eine Anfrage zum Zurücksetzen deines Passworts gestellt.</p>
        <p>Klicke auf den folgenden Link, um ein neues Passwort zu vergeben:</p>
        <p style="margin: 20px 0;">
          <a href="${resetLink}" 
             style="background-color: #4CAF50; color: white; padding: 12px 24px; text-decoration: none; border-radius: 4px; display: inline-block;">
            Passwort zurücksetzen
          </a>
        </p>
        <p style="color: #666; font-size: 14px;">
          Dieser Link ist <strong>1 Stunde</strong> gültig.<br>
          Falls du diese Anfrage nicht gestellt hast, ignoriere diese E-Mail einfach.
        </p>
        <hr style="border: none; border-top: 1px solid #eee; margin: 20px 0;">
        <p style="color: #999; font-size: 12px;">
          Falls der Button nicht funktioniert, kopiere diesen Link in deinen Browser:<br>
          <a href="${resetLink}">${resetLink}</a>
        </p>
      </div>
    `,
  });
};

const sendFriendlyMatchInvitationEmail = async ({
  toEmails,
  fromClubName,
  toClubName,
  proposedDate,
  proposedStartTime,
  proposedMatchName,
  message,
}) => {
  const recipientList = Array.isArray(toEmails) ? toEmails.filter(Boolean) : [toEmails].filter(Boolean);
  if (!recipientList.length) return;

  const appUrl = process.env.BASE_URL || process.env.PUBLIC_SITE_URL || 'https://tt-tagebuch.de';
  const timeLabel = proposedStartTime ? ` um ${proposedStartTime}` : '';
  const messageHtml = message
    ? `<p style="margin-top: 12px;"><strong>Nachricht:</strong><br>${String(message).replace(/</g, '&lt;').replace(/>/g, '&gt;')}</p>`
    : '';

  await sendMail({
    to: recipientList.join(','),
    subject: `Freundschaftsspiel-Einladung: ${fromClubName} -> ${toClubName}`,
    html: `
      <div style="font-family: Arial, sans-serif; max-width: 700px; margin: 0 auto;">
        <h2 style="color: #1f2937;">Neue Freundschaftsspiel-Einladung</h2>
        <p>Der Verein <strong>${fromClubName}</strong> hat euren Verein zu einem Freundschaftsspiel eingeladen.</p>
        <ul>
          <li><strong>Match:</strong> ${proposedMatchName}</li>
          <li><strong>Datum:</strong> ${proposedDate}${timeLabel}</li>
        </ul>
        ${messageHtml}
        <p style="margin-top: 16px;">Bitte in der App annehmen oder ablehnen:</p>
        <p>
          <a href="${appUrl}/friendly-matches"
             style="background-color:#2563eb;color:#fff;padding:10px 16px;text-decoration:none;border-radius:6px;display:inline-block;">
            Zur Einladung
          </a>
        </p>
      </div>
    `,
  });
};

const escapeHtml = (value) => String(value ?? '')
  .replace(/&/g, '&amp;')
  .replace(/</g, '&lt;')
  .replace(/>/g, '&gt;')
  .replace(/"/g, '&quot;');

const sendMobileFeedbackEmail = async ({
  message,
  screen,
  clubId,
  appVersion,
  platform,
  backendBaseUrl,
  user,
}) => {
  await sendMail({
    to: 'tsschulz2001@gmail.com',
    subject: `Android Feedback${screen ? ` - ${screen}` : ''}`,
    html: `
      <div style="font-family: Arial, sans-serif; max-width: 760px; margin: 0 auto;">
        <h2 style="color:#1f2937;">Android Feedback</h2>
        <p><strong>Seite:</strong> ${escapeHtml(screen || '-')}</p>
        <p><strong>Verein-ID:</strong> ${escapeHtml(clubId ?? '-')}</p>
        <p><strong>User:</strong> ${escapeHtml(user?.username || user?.email || user?.id || '-')}</p>
        <p><strong>User-ID:</strong> ${escapeHtml(user?.id || '-')}</p>
        <p><strong>App-Version:</strong> ${escapeHtml(appVersion || '-')}</p>
        <p><strong>Plattform:</strong> ${escapeHtml(platform || 'Android')}</p>
        <p><strong>Backend:</strong> ${escapeHtml(backendBaseUrl || '-')}</p>
        <hr style="border:none;border-top:1px solid #e5e7eb;margin:16px 0;">
        <h3 style="color:#1f2937;">Meldung</h3>
        <div style="white-space:pre-wrap;background:#f9fafb;border:1px solid #e5e7eb;border-radius:8px;padding:12px;">${escapeHtml(message)}</div>
      </div>
    `,
  });
};

const sendClubCommunicationEmail = async ({
  to,
  subject,
  text,
  html,
  replyTo,
}) => {
  return sendMail({
    to,
    subject,
    text,
    html,
    replyTo: replyTo || undefined,
  });
};

export { sendActivationEmail, sendPasswordResetEmail, sendFriendlyMatchInvitationEmail, sendMobileFeedbackEmail, sendClubCommunicationEmail };
