// utils/emailSender.js
const nodemailer = require('nodemailer');

/*
  Centralized email transport
  Configured for SSL (port 465)
*/
const transporter = nodemailer.createTransport({
  host: process.env.SMTP_HOST,
  port: 465,              // 🔒 FIXED
  secure: true,           // 🔒 REQUIRED for 465
  auth: {
    user: process.env.SMTP_USER,
    pass: process.env.SMTP_PASS
  },
  tls: {
    rejectUnauthorized: false // OK for now; tighten later
  }
});

/* ----------------------------------
   GENERIC SEND FUNCTION
---------------------------------- */
async function sendEmail({ to, subject, html }) {
  if (!to || !subject || !html) {
    throw new Error('Missing email parameters');
  }

  const emailNormalized = to.toLowerCase().trim();

  return transporter.sendMail({
    from: process.env.EMAIL_FROM || process.env.SMTP_USER,
    to: emailNormalized,
    subject,
    html
  });
}

/* ----------------------------------
   ORG VERIFICATION EMAIL
---------------------------------- */
async function sendOrganizationVerificationEmail({
  to,
  organizationName,
  verificationToken
}) {
  const verifyUrl =
    `${process.env.APP_BASE_URL}/organization/verify-email?token=${verificationToken}`;

  const html = `
    <p>Hello,</p>

    <p>Your organization <strong>${organizationName}</strong> has been registered.</p>

    <p>Please verify your email address by clicking the link below:</p>

    <p>
      <a href="${verifyUrl}">Verify Email</a>
    </p>

    <p>This link will expire in 24 hours.</p>

    <p>— GoCRM Team</p>
  `;

  await sendEmail({
    to,
    subject: 'Verify your organization email',
    html
  });
}

async function sendUserInviteEmail({ to, token }) {
  
  const url = `${process.env.APP_BASE_URL}/invite?token=${token}`;

  await sendEmail({
    to,
    subject: 'You have been invited to GoCRM',
    html: `
      <p>You have been invited to join an organization.</p>
      <a href="${url}">Accept Invite</a>
    `
  });
}

async function sendTempPassword({ to, token }) {
  
  await sendEmail({
    to,
    subject: 'Temporary Password',
    html: `
      <p>Admin has reset you password and below is your temporary password,

      <p>Password: "${token}".</p>
      <p> Please login to your account and reset your password.
    `
  });
}



module.exports = {
  sendEmail,
  sendOrganizationVerificationEmail,
  sendUserInviteEmail
};

