import nodemailer from 'nodemailer';
import handlebars from 'handlebars';
import fs from 'fs/promises';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

/**
 * Email Service
 * Nodemailer + Handlebars template alapú email küldés
 */
class EmailService {
  constructor() {
    // Nodemailer transporter létrehozása (Ethereal test SMTP)
    this.transporter = nodemailer.createTransport({
      host: 'smtp.ethereal.email',
      port: 587,
      secure: false, // TLS
      auth: {
        user: process.env.ETHEREAL_USER || 'your-test-email@ethereal.email',
        pass: process.env.ETHEREAL_PASS || 'your-test-password'
      }
    });

    console.log('📧 EmailService initialized with Ethereal SMTP');
  }

  /**
   * Template betöltése és renderelése
   * 
   * @param {string} templateName - Template fájl neve (.hbs nélkül)
   * @param {Object} data - Template adatok
   * @returns {Promise<string>} Renderelt HTML
   */
  async renderTemplate(templateName, data) {
    try {
      // Template fájl beolvasása
      const templatePath = path.join(__dirname, '..', '..', 'email-templates', `${templateName}.hbs`);
      const templateContent = await fs.readFile(templatePath, 'utf-8');

      // Handlebars compile és render
      const template = handlebars.compile(templateContent);
      return template(data);
    } catch (error) {
      console.error(`Template render error (${templateName}):`, error);
      throw new Error(`Failed to render email template: ${templateName}`);
    }
  }

  /**
   * Email küldés
   * 
   * @param {Object} options - { to, subject, html, text }
   * @returns {Promise<Object>} Nodemailer info objektum
   */
  async sendEmail(options) {
    try {
      const mailOptions = {
        from: '"Your App" <noreply@yourapp.com>',
        to: options.to,
        subject: options.subject,
        html: options.html,
        text: options.text || ''
      };

      const info = await this.transporter.sendMail(mailOptions);

      console.log('📧 Email sent:', {
        messageId: info.messageId,
        to: options.to,
        subject: options.subject,
        previewURL: nodemailer.getTestMessageUrl(info)
      });

      return info;
    } catch (error) {
      console.error('Email send error:', error);
      throw new Error('Failed to send email');
    }
  }

  /**
   * Welcome email küldése új user számára
   * 
   * @param {string} userEmail - User email címe
   * @param {string} userName - User neve
   * @returns {Promise<Object>}
   */
  async sendWelcomeEmail(userEmail, userName) {
    try {
      const html = await this.renderTemplate('welcome', {
        userName,
        appName: 'Your App',
        loginUrl: `${process.env.APP_URL || 'http://localhost:3000'}/login`
      });

      return await this.sendEmail({
        to: userEmail,
        subject: 'Welcome to Your App! 🎉',
        html,
        text: `Welcome ${userName}! Thank you for registering.`
      });
    } catch (error) {
      console.error('Welcome email error:', error);
      // Ne dobjunk hibát, csak loggoljuk
      // Az email küldés hibája ne akadályozza meg a regisztrációt
      return null;
    }
  }

  /**
   * Password reset email
   * 
   * @param {string} userEmail - User email címe
   * @param {string} resetToken - Password reset token
   * @returns {Promise<Object>}
   */
  async sendPasswordResetEmail(userEmail, resetToken) {
    try {
      const resetUrl = `${process.env.APP_URL || 'http://localhost:3000'}/reset-password?token=${resetToken}`;

      const html = await this.renderTemplate('password-reset', {
        resetUrl,
        expiryHours: 1
      });

      return await this.sendEmail({
        to: userEmail,
        subject: 'Password Reset Request 🔒',
        html,
        text: `Click the following link to reset your password: ${resetUrl}`
      });
    } catch (error) {
      console.error('Password reset email error:', error);
      return null;
    }
  }

  /**
   * Tesztelés: Email szolgáltatás ellenőrzése
   * 
   * @returns {Promise<boolean>}
   */
  async verify() {
    try {
      await this.transporter.verify();
      console.log('✅ Email service is ready');
      return true;
    } catch (error) {
      console.error('❌ Email service verification failed:', error);
      return false;
    }
  }
}
export { EmailService };
