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

// GET CLINIC SUMMARY REPORT (IKOSOYE NEZA BURUNDU)
router.get('/reports/summary', async (req, res) => {
    const { startDate, endDate } = req.query;

    try {
        // A. ABAGANGA N'ABARWAYI: Izi queries zizajya zizana imibare yose usesuye kuva kare,
        // NTA KAZU K'AMATARIKI KABABANGAMIYE kuko basabwa kugaragara buri gihe!
        const [doctorsCount] = await db.query('SELECT COUNT(*) as totalDocs FROM doctors');
        const [patientsCount] = await db.query('SELECT COUNT(*) as totalPats FROM patients');

        // Gutegura imibare y'izozi
        let totalAppointments = 0;
        let pendingAppointments = 0;

        // B. IZOZI (APPOINTMENTS): Izi zo zizajya zikurikiza amatariki gusa niba yahisemo
        if (startDate && endDate && startDate !== '' && endDate !== '' && startDate !== 'undefined' && endDate !== 'undefined') {
            
            // Niba umuntu yanditse amatariki, hapa hiyungurura izozi gusa zabaye icyo gihe
            const [appsCount] = await db.query('SELECT COUNT(*) as totalApps FROM appointments WHERE appointmentDate BETWEEN ? AND ?', [startDate, endDate]);
            const [pendingApps] = await db.query('SELECT COUNT(*) as pending FROM appointments WHERE appointmentDate BETWEEN ? AND ? AND status = "Pending"', [startDate, endDate]);
            
            totalAppointments = appsCount.totalApps || 0;
            pendingAppointments = pendingApps.pending || 0;

        } else {
            
            // Default: Niba amasanduku ari ubusa, izana izozi zose kuva kera
            const [appsCountAll] = await db.query('SELECT COUNT(*) as totalApps FROM appointments');
            const [pendingAppsAll] = await db.query('SELECT COUNT(*) as pending FROM appointments WHERE status = "Pending"');
            
            totalAppointments = appsCountAll.totalApps || 0;
            pendingAppointments = pendingAppsAll.pending || 0;
        }

        // Kohereza amakuru neza muri React
        return res.status(200).json({
            totalDoctors: doctorsCount.totalDocs || 0,
            totalPatients: patientsCount.totalPats || 0,
            totalAppointments: totalAppointments,
            pendingAppointments: pendingAppointments
        });

    } catch (err) {
        console.error('Error generating separate dynamic report summary:', err);
        return res.status(500).json({ message: 'Internal server error' });
    }
});

module.exports = router;
