const axios = require('axios');

// SMS Configuration
const SMS_CONFIG = {
    SENDER_ID: process.env.SMS_SENDER_ID || '8809617611338',
    API_BASE_URL: process.env.SMS_API_URL || 'https://xend.positiveapi.com/api/v3',
    TOKEN: process.env.SMS_API_TOKEN || '419|xFSHHY3vGlHDNE3XFijfExhQBpWsC64VsL51BYPO'
};

// Helper function to format phone number for Bangladesh
const formatBangladeshPhone = (phone) => {
    if (!phone) return null;
    
    // Remove all non-numeric characters
    let cleaned = phone.replace(/\D/g, '');
    
    // If it starts with 0, remove it
    if (cleaned.startsWith('0')) {
        cleaned = cleaned.substring(1);
    }
    
    // If it starts with 880, remove the 88 part
    if (cleaned.startsWith('880')) {
        cleaned = cleaned.substring(2);
    }
    
    // Ensure it's a valid Bangladeshi number (10 digits starting with 1)
    if (cleaned.length === 10 && cleaned.startsWith('1')) {
        return `+880${cleaned}`;
    }
    
    return null;
};

// Main SMS sending function - accepts message from frontend
const sendSMS = async (phoneNumber, message, options = {}) => {
    try {
        // Validate phone number
        if (!phoneNumber) {
            return { success: false, error: 'Phone number is required' };
        }

        // Format phone number
        let formattedPhone = phoneNumber;
        if (!phoneNumber.startsWith('+')) {
            formattedPhone = formatBangladeshPhone(phoneNumber);
            if (!formattedPhone) {
                return { success: false, error: 'Invalid Bangladeshi phone number' };
            }
        } else {
            formattedPhone = phoneNumber;
        }

        // Validate message
        if (!message) {
            return { success: false, error: 'Message is required' };
        }

        // Format phone for API (remove + and ensure 880 format)
        let apiPhone = formattedPhone.replace(/\D/g, '');
        if (apiPhone.startsWith('880')) {
            apiPhone = apiPhone;
        } else if (apiPhone.startsWith('1')) {
            apiPhone = '880' + apiPhone;
        }
        
        const url = `${SMS_CONFIG.API_BASE_URL}/sms/send`;
        
        // Prepare the request body
        const requestBody = {
            recipient: apiPhone,
            sender_id: options.senderId || SMS_CONFIG.SENDER_ID,
            message: message,
            ...options.additionalParams
        };

        console.log(`Sending SMS to ${apiPhone}: ${message.substring(0, 30)}...`);

        // Make POST request with Authorization header
        const response = await axios.post(url, requestBody, {
            headers: {
                'Authorization': `Bearer ${options.token || SMS_CONFIG.TOKEN}`,
                'Content-Type': 'application/json'
            },
            timeout: options.timeout || 10000 // 10 seconds timeout
        });
        
        // Check response status
        if (response.data && response.data.status === 'success') {
            return { 
                success: true, 
                data: response.data,
                message: 'SMS sent successfully',
                recipient: formattedPhone
            };
        } else {
            console.error('SMS sending failed:', response.data);
            return { 
                success: false, 
                error: 'SMS sending failed',
                details: response.data 
            };
        }
    } catch (error) {
        console.error('Error sending SMS:', error.response?.data || error.message);
        return { 
            success: false, 
            error: error.response?.data?.message || error.message,
            details: error.response?.data || error
        };
    }
};

// Send bulk SMS (optional)
const sendBulkSMS = async (messages) => {
    // messages: [{ phoneNumber, message, options }]
    const results = [];
    for (const msg of messages) {
        const result = await sendSMS(msg.phoneNumber, msg.message, msg.options);
        results.push(result);
        // Add small delay to avoid rate limiting
        await new Promise(resolve => setTimeout(resolve, 500));
    }
    return results;
};

// Verify SMS delivery status (optional)
const checkSMSStatus = async (messageId, options = {}) => {
    try {
        const url = `${SMS_CONFIG.API_BASE_URL}/sms/status/${messageId}`;
        
        const response = await axios.get(url, {
            headers: {
                'Authorization': `Bearer ${options.token || SMS_CONFIG.TOKEN}`,
                'Content-Type': 'application/json'
            }
        });
        
        return {
            success: true,
            status: response.data
        };
    } catch (error) {
        console.error('Error checking SMS status:', error);
        return {
            success: false,
            error: error.message
        };
    }
};

module.exports = {
    sendSMS,
    sendBulkSMS,
    checkSMSStatus,
    formatBangladeshPhone
};