// Mailtrap API Configuration
const MAILTRAP_API_URL = process.env.MAILTRAP_API_URL || 'https://send.api.mailtrap.io/api/send';
const MAILTRAP_API_TOKEN = process.env.MAILTRAP_API_TOKEN || 'cfbf65ba0e79a6d4f796e9fa91d9fa2e';
const MAILTRAP_FROM_EMAIL = process.env.MAILTRAP_FROM_EMAIL || 'hello@sigmaconnect.org';
const MAILTRAP_FROM_NAME = process.env.MAILTRAP_FROM_NAME || 'EMS App';

// Helper function to generate OTP (4 digits)
function generateOTP() {
    return Math.floor(1000 + Math.random() * 9000).toString();
}

// Helper function to send OTP email using Mailtrap API
function sendOTPEmail(email, otp) {
    // Validate email format
    if (!email || !email.includes('@')) {
        return Promise.reject(new Error('Invalid email address'));
    }

    const emailData = {
        from: {
            email: MAILTRAP_FROM_EMAIL,
            name: MAILTRAP_FROM_NAME
        },
        to: [
            {
                email: email
            }
        ],
        subject: 'Email Verification - EMS App',
        html: `
            <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px;">
                <h2 style="color: #333; margin-bottom: 20px;">Email Verification</h2>
                <p style="color: #666; font-size: 16px; line-height: 1.6;">Thank you for registering with our EMS App!</p>
                <p style="color: #666; font-size: 16px; line-height: 1.6;">Your verification code is:</p>
                <div style="background-color: #f4f4f4; padding: 20px; text-align: center; margin: 20px 0; border-radius: 8px;">
                    <h1 style="color: #0066cc; margin: 0; font-size: 32px; letter-spacing: 8px; font-weight: bold;">${otp}</h1>
                </div>
                <p style="color: #666; font-size: 14px; line-height: 1.6;">This 4-digit code will expire in 10 minutes. Please do not share this code with anyone.</p>
                <p style="color: #666; font-size: 14px; line-height: 1.6;">If you did not request this verification, please ignore this email.</p>
                <hr style="border: none; border-top: 1px solid #eee; margin: 20px 0;">
                <p style="color: #999; font-size: 12px; margin-top: 20px;">This is an automated message, please do not reply.</p>
            </div>
        `,
        category: 'OTP Verification'
    };

    // Use https module for HTTP requests (compatible with all Node.js versions)
    const https = require('https');
    const url = require('url');

    return new Promise((resolve, reject) => {
        const apiUrl = new url.URL(MAILTRAP_API_URL);
        const postData = JSON.stringify(emailData);

        const options = {
            hostname: apiUrl.hostname,
            path: apiUrl.pathname,
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${MAILTRAP_API_TOKEN}`,
                'Content-Type': 'application/json',
                'Content-Length': Buffer.byteLength(postData)
            }
        };

        const req = https.request(options, (res) => {
            let responseData = '';

            res.on('data', (chunk) => {
                responseData += chunk;
            });

            res.on('end', () => {
                if (res.statusCode >= 200 && res.statusCode < 300) {
                    try {
                        const result = JSON.parse(responseData);
                        console.log('Email sent successfully via Mailtrap:', result);
                        resolve(result);
                    } catch (parseError) {
                        console.log('Email sent successfully via Mailtrap (no JSON response)');
                        resolve(responseData);
                    }
                } else {
                    console.error('Mailtrap API error:', res.statusCode, responseData);
                    reject(new Error(`Mailtrap API error: ${res.statusCode} - ${responseData}`));
                }
            });
        });

        req.on('error', (error) => {
            console.error('Error sending email via Mailtrap:', error);
            reject(error);
        });

        req.write(postData);
        req.end();
    });
}

// Helper function to send dispatch notification email to client
function sendDispatchEmail(email, clientName, dispatchData) {
    // Validate email format
    if (!email || !email.includes('@')) {
        return Promise.reject(new Error('Invalid email address'));
    }

    const { request_id, ambulance_id, driver_id, dispatch_id, location, destination } = dispatchData;

    const emailData = {
        from: {
            email: MAILTRAP_FROM_EMAIL,
            name: MAILTRAP_FROM_NAME
        },
        to: [
            {
                email: email
            }
        ],
        subject: 'Ambulance Dispatched - EMS App',
        html: `
            <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px;">
                <h2 style="color: #333; margin-bottom: 20px;">Ambulance Dispatched</h2>
                <p style="color: #666; font-size: 16px; line-height: 1.6;">Dear ${clientName || 'Valued Client'},</p>
                <p style="color: #666; font-size: 16px; line-height: 1.6;">Your ambulance request has been successfully dispatched!</p>
                
                <div style="background-color: #f4f4f4; padding: 20px; margin: 20px 0; border-radius: 8px;">
                    <h3 style="color: #0066cc; margin-top: 0;">Dispatch Details</h3>
                    <p style="color: #666; font-size: 14px; line-height: 1.8; margin: 8px 0;">
                        <strong>Request ID:</strong> #${request_id}
                    </p>
                    <p style="color: #666; font-size: 14px; line-height: 1.8; margin: 8px 0;">
                        <strong>Dispatch ID:</strong> #${dispatch_id}
                    </p>
                    <p style="color: #666; font-size: 14px; line-height: 1.8; margin: 8px 0;">
                        <strong>Pickup Location:</strong> ${location || 'N/A'}
                    </p>
                    <p style="color: #666; font-size: 14px; line-height: 1.8; margin: 8px 0;">
                        <strong>Destination:</strong> ${destination || 'N/A'}
                    </p>
                    <p style="color: #666; font-size: 14px; line-height: 1.8; margin: 8px 0;">
                        <strong>Ambulance ID:</strong> #${ambulance_id}
                    </p>
                    <p style="color: #666; font-size: 14px; line-height: 1.8; margin: 8px 0;">
                        <strong>Driver ID:</strong> #${driver_id}
                    </p>
                </div>
                
                <p style="color: #666; font-size: 14px; line-height: 1.6;">The ambulance is on its way to your location. Please ensure you are ready for pickup.</p>
                <p style="color: #666; font-size: 14px; line-height: 1.6;">If you have any questions or need to make changes, please contact our support team immediately.</p>
                
                <hr style="border: none; border-top: 1px solid #eee; margin: 20px 0;">
                <p style="color: #999; font-size: 12px; margin-top: 20px;">This is an automated message, please do not reply.</p>
            </div>
        `,
        category: 'Dispatch Notification'
    };

    // Use https module for HTTP requests
    const https = require('https');
    const url = require('url');

    return new Promise((resolve, reject) => {
        const apiUrl = new url.URL(MAILTRAP_API_URL);
        const postData = JSON.stringify(emailData);

        const options = {
            hostname: apiUrl.hostname,
            path: apiUrl.pathname,
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${MAILTRAP_API_TOKEN}`,
                'Content-Type': 'application/json',
                'Content-Length': Buffer.byteLength(postData)
            }
        };

        const req = https.request(options, (res) => {
            let responseData = '';

            res.on('data', (chunk) => {
                responseData += chunk;
            });

            res.on('end', () => {
                if (res.statusCode >= 200 && res.statusCode < 300) {
                    try {
                        const result = JSON.parse(responseData);
                        console.log('Dispatch email sent successfully via Mailtrap:', result);
                        resolve(result);
                    } catch (parseError) {
                        console.log('Dispatch email sent successfully via Mailtrap (no JSON response)');
                        resolve(responseData);
                    }
                } else {
                    console.error('Mailtrap API error:', res.statusCode, responseData);
                    reject(new Error(`Mailtrap API error: ${res.statusCode} - ${responseData}`));
                }
            });
        });

        req.on('error', (error) => {
            console.error('Error sending dispatch email via Mailtrap:', error);
            reject(error);
        });

        req.write(postData);
        req.end();
    });
}

// Helper function to send notification email to developers
function sendDeveloperNotificationEmail(status, requestData) {
    const { id, request_by, location, destination, status: requestStatus, created_at } = requestData;
    
    const emailData = {
        from: {
            email: MAILTRAP_FROM_EMAIL,
            name: MAILTRAP_FROM_NAME
        },
        to: [
            {
                email: 'andrew@sigmagroupmw.com'
            },
            {
                email: 'chirambol@masm.mw'
            }
        ],
        subject: `EMS Request Dispatched - Request #${id}`,
        html: `
            <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px;">
                <h2 style="color: #333; margin-bottom: 20px;">EMS Request Dispatched</h2>
                <p style="color: #666; font-size: 16px; line-height: 1.6;">A request has been dispatched in the EMS system.</p>
                
                <div style="background-color: #f4f4f4; padding: 20px; margin: 20px 0; border-radius: 8px;">
                    <h3 style="color: #0066cc; margin-top: 0;">Request Details</h3>
                    <p style="color: #666; font-size: 14px; line-height: 1.8; margin: 8px 0;">
                        <strong>Request ID:</strong> #${id}
                    </p>
                    <p style="color: #666; font-size: 14px; line-height: 1.8; margin: 8px 0;">
                        <strong>Pickup Location:</strong> ${location || 'N/A'}
                    </p>
                    <p style="color: #666; font-size: 14px; line-height: 1.8; margin: 8px 0;">
                        <strong>Destination:</strong> ${destination || 'N/A'}
                    </p>
                </div>
                
                <hr style="border: none; border-top: 1px solid #eee; margin: 20px 0;">
                <p style="color: #999; font-size: 12px; margin-top: 20px;">This is an automated message, please do not reply.</p>
            </div>
        `,
        category: 'Notification'
    };

    // Use https module for HTTP requests
    const https = require('https');
    const url = require('url');

    return new Promise((resolve, reject) => {
        const apiUrl = new url.URL(MAILTRAP_API_URL);
        const postData = JSON.stringify(emailData);

        const options = {
            hostname: apiUrl.hostname,
            path: apiUrl.pathname,
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${MAILTRAP_API_TOKEN}`,
                'Content-Type': 'application/json',
                'Content-Length': Buffer.byteLength(postData)
            }
        };

        const req = https.request(options, (res) => {
            let responseData = '';

            res.on('data', (chunk) => {
                responseData += chunk;
            });

            res.on('end', () => {
                if (res.statusCode >= 200 && res.statusCode < 300) {
                    try {
                        const result = JSON.parse(responseData);
                        console.log(`Developer notification email sent successfully (${status}):`, result);
                        resolve(result);
                    } catch (parseError) {
                        console.log(`Developer notification email sent successfully (${status}) (no JSON response)`);
                        resolve(responseData);
                    }
                } else {
                    console.error('Mailtrap API error:', res.statusCode, responseData);
                    reject(new Error(`Mailtrap API error: ${res.statusCode} - ${responseData}`));
                }
            });
        });

        req.on('error', (error) => {
            console.error(`Error sending developer notification email (${status}):`, error);
            reject(error);
        });

        req.write(postData);
        req.end();
    });
}

// Generic email sending function (same implementation as sendDeveloperNotificationEmail)
function sendEmail(emailData) {
    // Use https module for HTTP requests
    const https = require('https');
    const url = require('url');

    return new Promise((resolve, reject) => {
        const apiUrl = new url.URL(MAILTRAP_API_URL);
        const postData = JSON.stringify(emailData);

        const options = {
            hostname: apiUrl.hostname,
            path: apiUrl.pathname,
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${MAILTRAP_API_TOKEN}`,
                'Content-Type': 'application/json',
                'Content-Length': Buffer.byteLength(postData)
            }
        };

        const req = https.request(options, (res) => {
            let responseData = '';

            res.on('data', (chunk) => {
                responseData += chunk;
            });

            res.on('end', () => {
                if (res.statusCode >= 200 && res.statusCode < 300) {
                    try {
                        const result = JSON.parse(responseData);
                        console.log('Email sent successfully:', result);
                        resolve(result);
                    } catch (parseError) {
                        console.log('Email sent successfully (no JSON response)');
                        resolve(responseData);
                    }
                } else {
                    console.error('Mailtrap API error:', res.statusCode, responseData);
                    reject(new Error(`Mailtrap API error: ${res.statusCode} - ${responseData}`));
                }
            });
        });

        req.on('error', (error) => {
            console.error('Error sending email:', error);
            reject(error);
        });

        req.write(postData);
        req.end();
    });
}

// Helper function to send patient report email with access code
function sendPatientReportEmail(email, code) {
    // Validate email format
    if (!email || !email.includes('@')) {
        return Promise.reject(new Error('Invalid email address'));
    }

    const emailData = {
        from: {
            email: MAILTRAP_FROM_EMAIL,
            name: MAILTRAP_FROM_NAME
        },
        to: [
            {
                email: email
            }
        ],
        subject: 'Patient Report Access - EMS App',
        html: `
            <div style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px;">
                <h2 style="color: #333; margin-bottom: 20px;">Patient Report Access</h2>
                <p style="color: #666; font-size: 16px; line-height: 1.6;">A patient report has been shared with you for access.</p>
                
                <div style="background-color: #f4f4f4; padding: 20px; margin: 20px 0; border-radius: 8px;">
                    <h3 style="color: #0066cc; margin-top: 0;">Access Information</h3>
                    <p style="color: #666; font-size: 14px; line-height: 1.8; margin: 8px 0;">
                        <strong>Access Code:</strong> <span style="background-color: #0066cc; color: white; padding: 4px 8px; border-radius: 4px; font-weight: bold; letter-spacing: 1px;">${code}</span>
                    </p>
                    <p style="color: #666; font-size: 14px; line-height: 1.8; margin: 8px 0;">
                        <strong>Access URL:</strong> <a href="https://masm-dashboard.vercel.app/patient-report-request" style="color: #0066cc; text-decoration: none;">https://masm-dashboard.vercel.app/patient-report-request</a>
                    </p>
                </div>
                
                <p style="color: #666; font-size: 14px; line-height: 1.6;">Use the access code above to view the patient report at the provided URL.</p>
                <p style="color: #666; font-size: 14px; line-height: 1.6;">This access code is single-use and will expire after 24 hours for security reasons.</p>
                <p style="color: #666; font-size: 14px; line-height: 1.6;">If you did not request this access, please contact our support team immediately.</p>
                
                <hr style="border: none; border-top: 1px solid #eee; margin: 20px 0;">
                <p style="color: #999; font-size: 12px; margin-top: 20px;">This is an automated message, please do not reply.</p>
            </div>
        `,
        category: 'Patient Report Access'
    };

    // Use https module for HTTP requests
    const https = require('https');
    const url = require('url');

    return new Promise((resolve, reject) => {
        const apiUrl = new url.URL(MAILTRAP_API_URL);
        const postData = JSON.stringify(emailData);

        const options = {
            hostname: apiUrl.hostname,
            path: apiUrl.pathname,
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${MAILTRAP_API_TOKEN}`,
                'Content-Type': 'application/json',
                'Content-Length': Buffer.byteLength(postData)
            }
        };

        const req = https.request(options, (res) => {
            let responseData = '';

            res.on('data', (chunk) => {
                responseData += chunk;
            });

            res.on('end', () => {
                if (res.statusCode >= 200 && res.statusCode < 300) {
                    try {
                        const result = JSON.parse(responseData);
                        console.log('Patient report email sent successfully:', result);
                        resolve(result);
                    } catch (parseError) {
                        console.log('Patient report email sent successfully (no JSON response)');
                        resolve(responseData);
                    }
                } else {
                    console.error('Mailtrap API error:', res.statusCode, responseData);
                    reject(new Error(`Mailtrap API error: ${res.statusCode} - ${responseData}`));
                }
            });
        });

        req.on('error', (error) => {
            console.error('Error sending patient report email:', error);
            reject(error);
        });

        req.write(postData);
        req.end();
    });
}

module.exports = {
    generateOTP,
    sendOTPEmail,
    sendDispatchEmail,
    sendDeveloperNotificationEmail,
    sendEmail,
    sendPatientReportEmail
};
