const ApprovedHealthCareEmail = require('../models/ApprovedHealthCareEmail');

const approvedHealthCareEmailController = {
    // Get all approved health care emails
    getAll: async (req, res) => {
        try {
            const emails = await ApprovedHealthCareEmail.findAll();
            res.json(emails);
        } catch (error) {
            console.error('Error fetching approved health care emails:', error);
            res.status(500).json({ error: 'Internal server error' });
        }
    },

    // Get approved health care email by ID
    getById: async (req, res) => {
        try {
            const { id } = req.params;
            
            if (!id) {
                return res.status(400).json({ error: 'ID is required' });
            }

            const email = await ApprovedHealthCareEmail.findById(id);
            
            if (!email) {
                return res.status(404).json({ error: 'Approved health care email not found' });
            }

            res.json(email);
        } catch (error) {
            console.error('Error fetching approved health care email:', error);
            res.status(500).json({ error: 'Internal server error' });
        }
    },

    // Create new approved health care email
    create: async (req, res) => {
        try {
            const { health_care_name, email } = req.body;

            if (!health_care_name || !email) {
                return res.status(400).json({ error: 'Health care name 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' });
            }

            const id = await ApprovedHealthCareEmail.create({ health_care_name, email });
            const newEmail = await ApprovedHealthCareEmail.findById(id);
            
            res.status(201).json(newEmail);
        } catch (error) {
            console.error('Error creating approved health care email:', error);
            res.status(500).json({ error: 'Internal server error' });
        }
    },

    // Delete approved health care email
    delete: async (req, res) => {
        try {
            const { id } = req.params;
            
            if (!id) {
                return res.status(400).json({ error: 'ID is required' });
            }

            const deleted = await ApprovedHealthCareEmail.delete(id);
            
            if (!deleted) {
                return res.status(404).json({ error: 'Approved health care email not found' });
            }

            res.json({ message: 'Approved health care email deleted successfully' });
        } catch (error) {
            console.error('Error deleting approved health care email:', error);
            res.status(500).json({ error: 'Internal server error' });
        }
    }
};

module.exports = approvedHealthCareEmailController;
