const nodemailer = require('nodemailer');

class EmailService {
    constructor() {
        this.transporter = null;
        this.init();
    }

    async init() {
        // For development/local, we might simulate or use ethereal
        // If config provided in env, use that.
        // Defaults to console logging for safety in this demo.
    }

    async sendPasswordReset(to, resetLink) {
        console.log('---------------------------------------------------');
        console.log('📧 MOCK EMAIL SERVICE - PASSWORD RESET');
        console.log(`To: ${to}`);
        console.log(`Subject: Recuperar Contraseña CRM`);
        console.log(`Body: Has solicitado restablecer tu contraseña.`);
        console.log(`Haz clic aquí: ${resetLink}`);
        console.log('---------------------------------------------------');

        // Allow real sending if env vars present (stubbed for future)
        if (process.env.SMTP_HOST) {
            if (!this.transporter) {
                this.transporter = nodemailer.createTransport({
                    host: process.env.SMTP_HOST,
                    port: process.env.SMTP_PORT,
                    secure: process.env.SMTP_SECURE === 'true',
                    auth: {
                        user: process.env.SMTP_USER,
                        pass: process.env.SMTP_PASS,
                    },
                });
            }

            try {
                await this.transporter.sendMail({
                    from: '"CRM Servicio" <noreply@crm.local>',
                    to,
                    subject: 'Recuperar Contraseña',
                    html: `<p>Haz clic en el siguiente enlace para restablecer tu contraseña:</p><p><a href="${resetLink}">${resetLink}</a></p>`,
                });
            } catch (error) {
                console.error('Failed to send real email (fallback to log success):', error);
            }
        }
    }

    async sendUserWelcome({ to, name, code, password, role }) {
        console.log('---------------------------------------------------');
        console.log('📧 MOCK EMAIL SERVICE - USER WELCOME');
        console.log(`To: ${to}`);
        console.log(`Subject: Bienvenido al CRM`);
        console.log(`Body: Hola ${name || ''}`.trim());
        console.log(`Rol: ${role || ''}`.trim());
        console.log(`Codigo: ${code || ''}`.trim());
        console.log(`Password temporal: ${password || ''}`.trim());
        console.log('Puedes cambiar tu password en Ajustes.');
        console.log('---------------------------------------------------');

        if (process.env.SMTP_HOST) {
            if (!this.transporter) {
                this.transporter = nodemailer.createTransport({
                    host: process.env.SMTP_HOST,
                    port: process.env.SMTP_PORT,
                    secure: process.env.SMTP_SECURE === 'true',
                    auth: {
                        user: process.env.SMTP_USER,
                        pass: process.env.SMTP_PASS,
                    },
                });
            }

            try {
                await this.transporter.sendMail({
                    from: '"CRM Servicio" <noreply@crm.local>',
                    to,
                    subject: 'Bienvenido al CRM',
                    html: `
                        <p>Hola ${name || ''},</p>
                        <p>Tu cuenta fue creada con el rol <strong>${role || ''}</strong>.</p>
                        <p><strong>Codigo:</strong> ${code || ''}</p>
                        <p><strong>Password temporal:</strong> ${password || ''}</p>
                        <p>Recuerda cambiar tu password en Ajustes.</p>
                    `
                });
            } catch (error) {
                console.error('Failed to send real email (fallback to log success):', error);
            }
        }
    }

    async sendUserVerification({ to, name, code }) {
        console.log('---------------------------------------------------');
        console.log('📧 MOCK EMAIL SERVICE - USER VERIFICATION');
        console.log(`To: ${to}`);
        console.log(`Subject: Verificacion de cuenta`);
        console.log(`Body: Hola ${name || ''}`.trim());
        console.log(`Codigo: ${code || ''}`.trim());
        console.log('Tu cuenta esta activa. Si no reconoces este correo, responde a soporte.');
        console.log('---------------------------------------------------');

        if (process.env.SMTP_HOST) {
            if (!this.transporter) {
                this.transporter = nodemailer.createTransport({
                    host: process.env.SMTP_HOST,
                    port: process.env.SMTP_PORT,
                    secure: process.env.SMTP_SECURE === 'true',
                    auth: {
                        user: process.env.SMTP_USER,
                        pass: process.env.SMTP_PASS,
                    },
                });
            }

            try {
                await this.transporter.sendMail({
                    from: '"CRM Servicio" <noreply@crm.local>',
                    to,
                    subject: 'Verificacion de cuenta',
                    html: `
                        <p>Hola ${name || ''},</p>
                        <p>Tu cuenta esta activa.</p>
                        <p><strong>Codigo:</strong> ${code || ''}</p>
                        <p>Si no reconoces este correo, responde a soporte.</p>
                    `
                });
            } catch (error) {
                console.error('Failed to send real email (fallback to log success):', error);
            }
        }
    }

    async sendProgramReferralSummary({ to, ownerName, programType, referrals }) {
        const list = (referrals || []).map((ref, index) => `${index + 1}. ${ref.NombreCompleto || ref.name || ''} - ${ref.Telefono || ref.phone || ''}`).join('\n');
        console.log('---------------------------------------------------');
        console.log('📧 MOCK EMAIL SERVICE - PROGRAM REFERRALS');
        console.log(`To: ${to}`);
        console.log(`Subject: Referidos del programa ${programType}`);
        console.log(`Body: Hola ${ownerName || ''}`.trim());
        console.log(`Referidos:\n${list}`);
        console.log('---------------------------------------------------');

        if (process.env.SMTP_HOST) {
            if (!this.transporter) {
                this.transporter = nodemailer.createTransport({
                    host: process.env.SMTP_HOST,
                    port: process.env.SMTP_PORT,
                    secure: process.env.SMTP_SECURE === 'true',
                    auth: {
                        user: process.env.SMTP_USER,
                        pass: process.env.SMTP_PASS,
                    },
                });
            }

            try {
                await this.transporter.sendMail({
                    from: '"CRM Servicio" <noreply@crm.local>',
                    to,
                    subject: `Referidos del programa ${programType}`,
                    text: `Hola ${ownerName || ''}\n\nReferidos:\n${list}`,
                });
            } catch (error) {
                console.error('Failed to send referral summary email:', error);
            }
        }
    }

    async sendProgramDemoUpdate({ to, ownerName, programType, referredName, demoCount }) {
        console.log('---------------------------------------------------');
        console.log('📧 MOCK EMAIL SERVICE - PROGRAM DEMO UPDATE');
        console.log(`To: ${to}`);
        console.log(`Subject: Demostracion completada (${programType})`);
        console.log(`Body: Hola ${ownerName || ''}`.trim());
        console.log(`Referido: ${referredName || ''}`.trim());
        console.log(`Demos completadas: ${demoCount || 0}`);
        console.log('---------------------------------------------------');

        if (process.env.SMTP_HOST) {
            if (!this.transporter) {
                this.transporter = nodemailer.createTransport({
                    host: process.env.SMTP_HOST,
                    port: process.env.SMTP_PORT,
                    secure: process.env.SMTP_SECURE === 'true',
                    auth: {
                        user: process.env.SMTP_USER,
                        pass: process.env.SMTP_PASS,
                    },
                });
            }

            try {
                await this.transporter.sendMail({
                    from: '"CRM Servicio" <noreply@crm.local>',
                    to,
                    subject: `Demostracion completada (${programType})`,
                    text: `Hola ${ownerName || ''}\n\nReferido: ${referredName || ''}\nDemos completadas: ${demoCount || 0}`,
                });
            } catch (error) {
                console.error('Failed to send demo update email:', error);
            }
        }
    }
}

module.exports = new EmailService();
