const { EmailLog } = require('../models/foundation');
const { Client, ContactPerson } = require('../models/client');
const { logAction } = require('../utils/logger');

exports.sendWelcomeEmail = async (user, plainPassword, companyName = 'Finance Pro') => {
    const { welcomeEmailTemplate } = require('../utils/emailTemplates');

    let ccEmails = [];
    if (user.clientId) {
        const client = await Client.findByPk(user.clientId, {
            include: [{ model: ContactPerson, as: 'contactPersons' }]
        });
        if (client && client.contactPersons) {
            ccEmails = client.contactPersons.map(cp => cp.email).filter(e => !!e);
        }
    }

    let htmlContent = '';
    if (welcomeEmailTemplate) {
        htmlContent = welcomeEmailTemplate(user, plainPassword, { name: companyName });
    } else {
        htmlContent = `Welcome! Your password is: ${plainPassword}`;
    }

    console.log('---------------------------------------------------');
    console.log(`[MOCK EMAIL] To: ${user.email}`);
    if (ccEmails.length > 0) {
        console.log(`[MOCK EMAIL] CC: ${ccEmails.join(', ')}`);
    }
    console.log(`[MOCK EMAIL] Subject: Welcome to ${companyName} - Your Credentials`);
    console.log(`[MOCK EMAIL] Password: ${plainPassword}`);
    console.log('---------------------------------------------------');

    try {
        await EmailLog.create({
            to: user.email,
            subject: `Welcome to ${companyName}`,
            module: 'AUTH',
            referenceId: user.id,
            status: 'Success',
            errorMessage: null
        });
    } catch (err) {
        console.error('Failed to log email:', err);
    }

    return true;
};

exports.sendPasswordResetEmail = async (user, plainPassword, companyName = 'Finance Pro') => {
    let ccEmails = [];
    if (user.clientId) {
        const client = await Client.findByPk(user.clientId, {
            include: [{ model: ContactPerson, as: 'contactPersons' }]
        });
        if (client && client.contactPersons) {
            ccEmails = client.contactPersons.map(cp => cp.email).filter(e => !!e);
        }
    }

    console.log('---------------------------------------------------');
    console.log(`[MOCK EMAIL] To: ${user.email}`);
    if (ccEmails.length > 0) {
        console.log(`[MOCK EMAIL] CC: ${ccEmails.join(', ')}`);
    }
    console.log(`[MOCK EMAIL] Subject: Password Reset Request`);
    console.log(`[MOCK EMAIL] New Password: ${plainPassword}`);
    console.log('---------------------------------------------------');
    try {
        await EmailLog.create({
            to: user.email,
            subject: `Password Reset`,
            module: 'AUTH',
            referenceId: user.id,
            status: 'Success',
            errorMessage: null
        });
    } catch (err) {
        console.error('Failed to log email:', err);
    }
    return true;
};
exports.sendPasswordResetLink = async (user, token, companyName = 'Finance Pro') => {
    const resetUrl = `${process.env.FRONTEND_URL || 'http://localhost:3000'}/reset-password?token=${token}`;

    console.log('---------------------------------------------------');
    console.log(`[MOCK EMAIL] To: ${user.email}`);
    console.log(`[MOCK EMAIL] Subject: Password Reset Request`);
    console.log(`[MOCK EMAIL] Link: ${resetUrl}`);
    console.log('---------------------------------------------------');

    try {
        await EmailLog.create({
            to: user.email,
            subject: `Password Reset Request`,
            module: 'AUTH',
            referenceId: user.id,
            status: 'Success'
        });
    } catch (err) {
        console.error('Failed to log reset email:', err);
    }
    return true;
};

exports.sendPasswordResetOTP = async (user, otp) => {
    console.log('---------------------------------------------------');
    console.log(`[MOCK SMS] To: ${user.phone}`);
    console.log(`[MOCK SMS] Message: Your password reset OTP is ${otp}. Valid for 10 minutes.`);
    console.log('---------------------------------------------------');

    // We could add an SMSLog model here, but for now we log reset attempts in AuditLog
    return true;
};
