const db = require('../db');
const crypto = require('crypto');
const { sendPatientReportEmail } = require('../config/email');

const patientReportEmailController = {
    // Send patient report email
    sendEmail: async (req, res) => {
        const { patient_report_id, email } = req.body;

        // Validate input
        if (!patient_report_id || !email) {
            return res.status(400).json({ error: 'Patient report ID and email are required' });
        }

        // Validate email format
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (!emailRegex.test(email)) {
            return res.status(400).json({ error: 'Invalid email format' });
        }

        // Generate 8-character alphanumeric code with capital letters
        const generateCode = () => {
            const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
            let code = '';
            for (let i = 0; i < 8; i++) {
                code += chars.charAt(Math.floor(Math.random() * chars.length));
            }
            return code;
        };

        const code = generateCode();

        try {
            // Insert into patient_reports_emails table
            const query = `
                INSERT INTO patient_reports_emails (patient_report_id, email, code)
                VALUES (?, ?, ?)
            `;

            const result = await db.execute(query, [patient_report_id, email, code]);
            
            // Send actual email with URL and code
            try {
                await sendPatientReportEmail(email, code);
                console.log(`Patient report email sent to ${email} with code ${code}`);
            } catch (emailError) {
                console.error('Error sending patient report email:', emailError);
                // Still return success for database insertion, but log email error
            }
            
            res.status(201).json({
                message: 'Patient report email sent successfully',
                id: result[0].insertId,
                patient_report_id,
                email,
                code
            });
        } catch (err) {
            console.error('Error inserting patient report email:', err);
            return res.status(500).json({ error: 'Failed to send patient report email' });
        }
    },

    // Get patient report emails by patient report ID
    getEmailsByReportId: async (req, res) => {
        const { patient_report_id } = req.params;

        try {
            const query = `
                SELECT id, email, code, created_at
                FROM patient_reports_emails
                WHERE patient_report_id = ?
                ORDER BY created_at DESC
            `;

            const results = await db.execute(query, [patient_report_id]);
            res.json(results[0]);
        } catch (err) {
            console.error('Error fetching patient report emails:', err);
            return res.status(500).json({ error: 'Failed to fetch patient report emails' });
        }
    },

    // Delete patient report email
    deleteEmail: async (req, res) => {
        const { id } = req.params;

        try {
            const query = `
                DELETE FROM patient_reports_emails
                WHERE id = ?
            `;

            const result = await db.execute(query, [id]);
            
            if (result[0].affectedRows === 0) {
                return res.status(404).json({ error: 'Patient report email not found' });
            }

            res.json({ message: 'Patient report email deleted successfully' });
        } catch (err) {
            console.error('Error deleting patient report email:', err);
            return res.status(500).json({ error: 'Failed to delete patient report email' });
        }
    }
};

module.exports = patientReportEmailController;
