const express = require('express');
const router = express.Router();
const db = require('../config/db');
const { verifyAdmin } = require('../middleware/authMiddleware');

// 1. ADD NEW DOCTOR (Cinganywe verifyAdmin ku mutekano usesuye)
router.post('/doctors', verifyAdmin, async (req, res) => {
    const { doctorName, specialization, email } = req.body;

    if (!doctorName || !specialization || !email) {
        return res.status(400).json({ message: 'All fields are required' });
    }

    try {
        await db.query(
            'INSERT INTO doctors (doctorName, specialization, email) VALUES (?, ?, ?)',
            [doctorName, specialization, email]
        );
        return res.status(201).json({ message: 'Doctor registered successfully!' });
    } catch (err) {
        console.error(err);
        return res.status(500).json({ message: 'Internal server error' });
    }
});

// 2. GET ALL DOCTORS (Iyi yo ifunguye bose bayirebe muri select dropdown menus)
router.get('/doctors', async (req, res) => {
    try {
        const [rows] = await db.query('SELECT * FROM doctors');
        return res.status(200).json(rows);
    } catch (err) {
        console.error(err);
        return res.status(500).json({ message: 'Internal server error' });
    }
});

// 3. DELETE DOCTOR (Ikosoranye isuku - Icinganywe verifyAdmin ku rugi runaka rukomeye)
router.delete('/doctors/:id', verifyAdmin, async (req, res) => {
    const { id } = req.params;
    try {
        const [result] = await db.query('DELETE FROM doctors WHERE DoctorId = ?', [id]);
        if (result.affectedRows === 0) {
            return res.status(404).json({ message: 'Doctor not found' });
        }
        return res.status(200).json({ message: 'Doctor removed successfully' });
    } catch (err) {
        console.error(err);
        return res.status(500).json({ message: 'Internal server error' });
    }
});

// 4. UPDATE DOCTOR INFO (Cinganywe verifyAdmin binyuze kuri Admin panel)
router.put('/doctors/:id', verifyAdmin, async (req, res) => {
    const { id } = req.params;
    const { doctorName, specialization, email } = req.body;

    if (!doctorName || !specialization || !email) {
        return res.status(400).json({ message: 'All fields are required for update' });
    }

    try {
        const [result] = await db.query(
            'UPDATE doctors SET doctorName = ?, specialization = ?, email = ? WHERE DoctorId = ?',
            [doctorName, specialization, email, id]
        );

        if (result.affectedRows === 0) {
            return res.status(404).json({ message: 'Doctor not found' });
        }

        return res.status(200).json({ message: 'Doctor records updated successfully!' });
    } catch (err) {
        console.error(err);
        return res.status(500).json({ message: 'Internal server error' });
    }
});

module.exports = router;
