const express = require('express');
const router = express.Router();
const db = require('../config/db');

// 1. CREATE NEW APPOINTMENT WITH BILLING
router.post('/appointments', async (req, res) => {
    const { PatientId, DoctorId, appointmentDate, prescription, consultationFee, medicationFee } = req.body;

    if (!PatientId || !DoctorId || !appointmentDate) {
        return res.status(400).json({ message: 'Patient, Doctor and Date are required' });
    }

    try {
        // Emeza ko tables zawe zifite izi columns muri MySQL: prescription, consultationFee, medicationFee.
        // Niba zitaziranyi, MySQL izabyanga. Cyangwa unyaruke muri phpMyAdmin uzi-alter-ingemo vuba!
        await db.query(`
            INSERT INTO appointments (PatientId, DoctorId, appointmentDate, status, prescription, consultationFee, medicationFee) 
            VALUES (?, ?, ?, "Pending", ?, ?, ?)`,
            [PatientId, DoctorId, appointmentDate, prescription || '', consultationFee || 0, medicationFee || 0]
        );
        return res.status(201).json({ message: 'Appointment booked successfully!' });
    } catch (err) {
        console.error(err);
        return res.status(500).json({ message: 'Internal server error' });
    }
});

// 2. GET ALL APPOINTMENTS WITH ALL FIELDS
router.get('/appointments', async (req, res) => {
    try {
        const [rows] = await db.query(`
            SELECT a.*, p.patientName, d.doctorName, d.specialization 
            FROM appointments a
            LEFT JOIN patients p ON a.PatientId = p.PatientId
            LEFT JOIN doctors d ON a.DoctorId = d.DoctorId
            ORDER BY a.appointmentDate DESC
        `);
        return res.status(200).json(rows);
    } catch (err) {
        console.error(err);
        return res.status(500).json({ message: 'Internal server error' });
    }
});

module.exports = router;
