const Setting = require('../models/setting.model');
const smsService = require('./sms.service');
const SmsTemplate = require('../models/smsTemplate.model');
const WhatsappTemplate = require('../models/whatsappTemplate.model');
const NotificationSettings = require('../models/notificationSettings.model');
const ErrorHandler = require('../utils/ErrorHandler');

/**
 * Send SMS using configured provider
 * @param {string} to - Phone number
 * @param {string} messageType - Type of message (e.g., 'booking_confirmation')
 * @param {object} variables - Variables to substitute in template
 * @returns {Promise<object>} - Send result
 */
const sendSMS = async (to, messageType, variables = {}) => {
    try {
        // Check if SMS is enabled for this event
        const notifSettings = await NotificationSettings.getByEventType(messageType);
        if (!notifSettings.channels.sms.enabled) {
            console.log(`ℹ️ SMS disabled for event: ${messageType}`);
            return {
                success: false,
                reason: 'SMS channel disabled for this event',
                messageType
            };
        }

        // Get settings
        const settings = await Setting.getSettingsWithDecryption();
        const smsConfig = settings?.messaging?.sms;

        if (!smsConfig || !smsConfig.enabled) {
            console.log('ℹ️ SMS service is globally disabled');
            return {
                success: false,
                reason: 'SMS service disabled',
                messageType
            };
        }

        // Get template
        const template = await SmsTemplate.getByMessageType(messageType);
        if (!template) {
            throw new ErrorHandler(`No SMS template found for: ${messageType}`, 404);
        }

        // Validate and substitute variables
        const validation = template.validateVariables(variables);
        if (!validation.valid) {
            console.warn(`⚠️ Template validation warning for ${messageType}:`, validation.message);
        }

        const message = template.substituteVariables(variables);

        // Send via sms.service (it will automatically route to correct provider)
        const result = await smsService.sendSms(to, message);

        return {
            ...result,
            messageType,
            templateName: template.templateName,
            channel: 'sms'
        };
    } catch (error) {
        console.error('❌ Failed to send SMS:', error.message);
        return {
            success: false,
            error: error.message,
            messageType,
            channel: 'sms'
        };
    }
};

/**
 * Send WhatsApp message using configured provider
 * @param {string} to - Phone number
 * @param {string} messageType - Type of message
 * @param {object} variables - Variables to substitute in template
 * @returns {Promise<object>} - Send result
 */
const sendWhatsApp = async (to, messageType, variables = {}) => {
    try {
        // Check if WhatsApp is enabled for this event
        const notifSettings = await NotificationSettings.getByEventType(messageType);
        if (!notifSettings.channels.whatsapp.enabled) {
            console.log(`ℹ️ WhatsApp disabled for event: ${messageType}`);
            return {
                success: false,
                reason: 'WhatsApp channel disabled for this event',
                messageType
            };
        }

        // Get settings
        const settings = await Setting.getSettingsWithDecryption();
        const whatsappConfig = settings?.messaging?.whatsapp;

        if (!whatsappConfig || !whatsappConfig.enabled) {
            console.log('ℹ️ WhatsApp service is globally disabled');
            return {
                success: false,
                reason: 'WhatsApp service disabled',
                messageType
            };
        }

        // Get template
        const template = await WhatsappTemplate.getByMessageType(messageType);
        if (!template) {
            throw new ErrorHandler(`No WhatsApp template found for: ${messageType}`, 404);
        }

        // Validate variables
        const validation = template.validateVariables(variables);
        if (!validation.valid) {
            console.warn(`⚠️ Template validation warning for ${messageType}:`, validation.message);
        }

        // Prepare options for WhatsApp
        const message = template.substituteVariables(variables);
        const options = {
            templateId: template.fast2smsTemplateId,
            contentSid: template.twilioContentSid,
            variables
        };

        // Send via sms.service (it will automatically route to correct provider)
        const result = await smsService.sendWhatsApp(to, message, options);

        return {
            ...result,
            messageType,
            templateName: template.templateName,
            channel: 'whatsapp'
        };
    } catch (error) {
        console.error('❌ Failed to send WhatsApp:', error.message);
        return {
            success: false,
            error: error.message,
            messageType,
            channel: 'whatsapp'
        };
    }
};

/**
 * Send notification across all enabled channels
 * @param {object} recipient - { email, phone }
 * @param {string} messageType - Type of message
 * @param {object} variables - Variables for templates
 * @returns {Promise<object>} - Results for all channels
 */
const sendNotification = async (recipient, messageType, variables = {}) => {
    const results = {
        email: null,
        sms: null,
        whatsapp: null
    };

    try {
        // Get notification settings
        const notifSettings = await NotificationSettings.getByEventType(messageType);

        // Send Email (if enabled)
        if (notifSettings.channels.email.enabled && recipient.email) {
            const emailService = require('./emailTemplateRenderer.service');
            results.email = await emailService.sendTemplateEmail(
                messageType,
                recipient.email,
                variables
            );
        }

        // Send SMS (if enabled)
        if (notifSettings.channels.sms.enabled && recipient.phone) {
            results.sms = await sendSMS(recipient.phone, messageType, variables);
        }

        // Send WhatsApp (if enabled)
        if (notifSettings.channels.whatsapp.enabled && recipient.phone) {
            results.whatsapp = await sendWhatsApp(recipient.phone, messageType, variables);
        }

        console.log(`📊 Notification sent for ${messageType}:`, {
            email: results.email?.success || false,
            sms: results.sms?.success || false,
            whatsapp: results.whatsapp?.success || false
        });

        return results;
    } catch (error) {
        console.error('❌ Error sending notification:', error.message);
        return results;
    }
};

module.exports = {
    sendSMS,
    sendWhatsApp,
    sendNotification
};
