import nodemailer from "nodemailer";
import { getEnv } from "@/lib/env";
import { getRescheduleConfirmationTemplate } from "@/lib/email/templates/reschedule-confirmation";
import { getDailyAgendaTemplate } from "@/lib/email/templates/daily-agenda";
import { getCourseInquiryTemplate } from "@/lib/email/templates/course-inquiry";

let transporter: nodemailer.Transporter | null = null;

function getTransporter(): nodemailer.Transporter {
  if (transporter) {
    return transporter;
  }

  const env = getEnv();

  transporter = nodemailer.createTransport({
    host: env.SMTP_HOST,
    port: env.SMTP_PORT,
    secure: false,
    auth: {
      user: env.SMTP_USER,
      pass: env.SMTP_PASS,
    },
    pool: true,
    maxConnections: 5,
    maxMessages: 100,
  });

  return transporter;
}

export async function sendEmail(to: string, subject: string, html: string): Promise<void> {
  const env = getEnv();
  const transporter = getTransporter();

  const mailOptions = {
    from: `"${env.SMTP_FROM_NAME}" <${env.SMTP_FROM_EMAIL}>`,
    to,
    subject,
    html,
  };

  let retries = 0;
  const maxRetries = 3;

  while (retries < maxRetries) {
    try {
      await transporter.sendMail(mailOptions);
      console.log(`[SMTP] Email sent to ${to}`);
      return;
    } catch (error) {
      retries++;
      if (retries === maxRetries) {
        console.error(`[SMTP] Failed to send email after ${maxRetries} retries:`, error);
        throw error;
      }
      const delay = Math.pow(2, retries) * 1000;
      await new Promise((resolve) => setTimeout(resolve, delay));
    }
  }
}

export async function sendRescheduleConfirmation(
  to: string,
  patientName: string,
  oldDate: Date,
  newDate: Date
): Promise<void> {
  const html = getRescheduleConfirmationTemplate(patientName, oldDate, newDate);
  await sendEmail(to, "Confirmación de Cambio de Cita - Gloria Niño Terapia", html);
}

export async function sendDailyAgenda(to: string, appointments: any[]): Promise<void> {
  const html = getDailyAgendaTemplate(appointments);
  const tomorrow = new Date();
  tomorrow.setDate(tomorrow.getDate() + 1);
  const formattedDate = tomorrow.toLocaleDateString("es-MX", {
    weekday: "long",
    year: "numeric",
    month: "long",
    day: "numeric",
  });
  await sendEmail(to, `📅 Agenda para el día ${formattedDate}`, html);
}

export async function sendCourseInquiry(
  to: string,
  name: string,
  email: string,
  course: string,
  message: string
): Promise<void> {
  const html = getCourseInquiryTemplate(name, email, course, message);
  await sendEmail(to, `🎓 Nueva Consulta sobre Cursos - ${course}`, html);
}
