﻿import nodemailer from 'nodemailer';

let transporter: nodemailer.Transporter | null = null;

function getTransporter() {
  if (!transporter) {
    console.log('Creating email transporter...');
    console.log('EMAIL_USER:', process.env.EMAIL_USER);
    
    transporter = nodemailer.createTransport({
      service: 'gmail',
      auth: {
        user: process.env.EMAIL_USER,
        pass: process.env.EMAIL_APP_PASSWORD,
      },
    });
  }
  return transporter;
}

export async function sendActivationEmail(to: string, name: string, token: string) {
  const frontendUrl = process.env.FRONTEND_URL || 'http://localhost:3000';
  const activationLink = `${frontendUrl}/activate-account?token=${token}`;

  const html = `
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="UTF-8">
      <title>Activate Your HRMS Account</title>
      <style>
        body { font-family: Arial, sans-serif; line-height: 1.6; }
        .container { max-width: 600px; margin: auto; padding: 20px; border: 1px solid #ddd; border-radius: 10px; }
        .header { background: #b828a0; color: white; padding: 20px; text-align: center; border-radius: 10px 10px 0 0; }
        .button { display: inline-block; padding: 12px 24px; background: #b828a0; color: white; text-decoration: none; border-radius: 5px; margin: 20px 0; }
        .footer { text-align: center; font-size: 12px; color: #666; margin-top: 20px; }
      </style>
    </head>
    <body>
      <div class="container">
        <div class="header">
          <h2>Welcome to HRMS</h2>
        </div>
        <div style="padding: 20px;">
          <p>Hello <strong>${name}</strong>,</p>
          <p>Your HRMS account has been created!</p>
          <p>Click the button below to activate your account and set your password:</p>
          <div style="text-align: center;">
            <a href="${activationLink}" class="button">Activate Account</a>
          </div>
          <p>Or copy this link: ${activationLink}</p>
          <p><strong>This link expires in 24 hours.</strong></p>
          <p>If you did not request this, please ignore this email.</p>
        </div>
        <div class="footer">
          <p>&copy; ${new Date().getFullYear()} HRMS System. All rights reserved.</p>
        </div>
      </div>
    </body>
    </html>
  `;

  try {
    const transporter = getTransporter();
    const info = await transporter.sendMail({
      from: `"HRMS System" <${process.env.EMAIL_USER}>`,
      to: to,
      subject: 'Activate Your HRMS Account',
      html: html,
    });
    console.log('Email sent to:', to, 'Message ID:', info.messageId);
    return { success: true, messageId: info.messageId };
  } catch (error) {
    console.error('Email error:', error);
    return { success: false, error: error.message };
  }
}

export async function sendTestEmail() {
  try {
    const transporter = getTransporter();
    const info = await transporter.sendMail({
      from: `"HRMS System" <${process.env.EMAIL_USER}>`,
      to: process.env.EMAIL_USER,
      subject: 'Test Email from HRMS',
      html: '<h1>Test Successful!</h1><p>Your email configuration is working.</p>',
    });
    console.log('Test email sent:', info.messageId);
    return { success: true, messageId: info.messageId };
  } catch (error) {
    console.error('Test email error:', error);
    return { success: false, error: error.message };
  }
}
