import nodemailer from 'nodemailer';

let transporter = null;

function isConfigured() {
  return Boolean(process.env.SMTP_HOST && process.env.SMTP_USER && process.env.SMTP_PASSWORD);
}

function getTransporter() {
  if (!transporter) {
    transporter = nodemailer.createTransport({
      host: process.env.SMTP_HOST,
      port: Number(process.env.SMTP_PORT) || 587,
      secure: process.env.SMTP_SECURE === 'true',
      auth: {
        user: process.env.SMTP_USER,
        pass: process.env.SMTP_PASSWORD,
      },
    });
  }
  return transporter;
}

// Best-effort by design — forgotPassword() always returns the same generic
// response to the client regardless of whether this succeeds, so a missing
// or broken SMTP config fails loudly in the server log rather than as an
// API error (which would leak configuration state to a requester).
export async function sendPasswordResetEmail(to, resetUrl) {
  if (!isConfigured()) {
    console.error(
      '✗ Password reset email not sent — SMTP is not configured. Set SMTP_HOST, SMTP_USER and SMTP_PASSWORD in backend/.env.'
    );
    return;
  }

  try {
    await getTransporter().sendMail({
      from: process.env.SMTP_FROM || process.env.SMTP_USER,
      to,
      subject: 'Reset your BMMG Records password',
      text: `Reset your password: ${resetUrl}\n\nThis link expires in 1 hour. If you didn't request this, you can ignore this email.`,
      html: `
        <p>Someone requested a password reset for your BMMG Records admin account.</p>
        <p><a href="${resetUrl}">Reset your password</a></p>
        <p>This link expires in 1 hour. If you didn't request this, you can ignore this email.</p>
      `,
    });
  } catch (err) {
    console.error('✗ Failed to send password reset email:', err.message);
  }
}
