import nodemailer from "nodemailer";

const EMAIL_USER = "mthigienizacao.marcos@gmail.com";
const EMAIL_PASSWORD = "tvbr rnhp nyum avhm";
const RECIPIENT_EMAIL = "mthigienizacao.marcos@gmail.com";

let transporter: nodemailer.Transporter | null = null;

function getTransporter() {
  if (!transporter) {
    transporter = nodemailer.createTransport({
      service: "gmail",
      auth: {
        user: EMAIL_USER,
        pass: EMAIL_PASSWORD,
      },
    });
  }
  return transporter;
}

export async function sendApplicationEmail(
  fullName: string,
  phone: string,
  jobTitle: string,
  rgFrontBase64: string,
  rgBackBase64: string
) {
  try {
    const transporter = getTransporter();

    // Convert base64 to buffer
    const rgFrontBuffer = Buffer.from(rgFrontBase64.split(",")[1] || rgFrontBase64, "base64");
    const rgBackBuffer = Buffer.from(rgBackBase64.split(",")[1] || rgBackBase64, "base64");

    const mailOptions = {
      from: EMAIL_USER,
      to: RECIPIENT_EMAIL,
      subject: `Nova Candidatura - ${fullName} para ${jobTitle}`,
      html: `
        <h2>Nova Candidatura Recebida</h2>
        <p><strong>Nome:</strong> ${fullName}</p>
        <p><strong>Telefone:</strong> ${phone}</p>
        <p><strong>Vaga:</strong> ${jobTitle}</p>
        <p><strong>Data:</strong> ${new Date().toLocaleString("pt-BR")}</p>
        <hr>
        <p>Documentos em anexo:</p>
        <ul>
          <li>RG - Frente</li>
          <li>RG - Verso</li>
        </ul>
      `,
      attachments: [
        {
          filename: `RG_Frente_${fullName.replace(/\s+/g, "_")}.jpg`,
          content: rgFrontBuffer,
        },
        {
          filename: `RG_Verso_${fullName.replace(/\s+/g, "_")}.jpg`,
          content: rgBackBuffer,
        },
      ],
    };

    const result = await transporter.sendMail(mailOptions);
    console.log("Email enviado com sucesso:", result.messageId);
    return true;
  } catch (error) {
    console.error("Erro ao enviar email:", error);
    throw error;
  }
}
