import nodemailer from "nodemailer";

const smtpHost = process.env.SMTP_HOST || "";
const smtpPort = Number(process.env.SMTP_PORT || 587);
const smtpUser = process.env.SMTP_USER || "";
const smtpPass = process.env.SMTP_PASS || "";
const smtpFrom = process.env.SMTP_FROM || "no-reply@example.com";

let transporter: nodemailer.Transporter | null = null;

export const getTransporter = () => {
  if (!transporter) {
    if (!smtpHost || !smtpUser || !smtpPass) {
      return null;
    }
    transporter = nodemailer.createTransport({
      host: smtpHost,
      port: smtpPort,
      secure: smtpPort === 465,
      auth: { user: smtpUser, pass: smtpPass },
    });
  }
  return transporter;
};

export const sendResetPasswordEmail = async (to: string, link: string) => {
  const t = getTransporter();
  const subject = "Reset your Bird Eye View password";
  const html = `
    <p>You requested to reset your Bird Eye View password.</p>
    <p>Click the link below to set a new password. If you didn't request this, you can ignore this email.</p>
    <p><a href="${link}">Reset Password</a></p>
    <p>This link will expire shortly for security reasons.</p>
  `;

  await t?.sendMail({ from: smtpFrom, to, subject, html });
};

export const sendInvitationEmail = async (to: string, link: string) => {
  const t = getTransporter();
  const subject = "You're invited to Bird Eye View";
  const html = `
    <p>You have been invited to join Bird Eye View.</p>
    <p>Click the link below to set your password and activate your account.</p>
    <p><a href="${link}">Accept Invitation</a></p>
    <p>This link will expire shortly for security reasons.</p>
  `;

  await t?.sendMail({ from: smtpFrom, to, subject, html });
};
