import { connection } from "../configs/db.js";
import { verifyCookies } from "../auth/auth.js";
import express from "express";

const reportRouter = express.Router();

// generate overall full report

reportRouter.get("/generate", verifyCookies, async (req, res) => {
    try {

        const { startDate, endDate } = req.query;

        let patients, appointments, medicalReports;

        if (startDate && endDate) {
            const sql = `
                SELECT * FROM patients
                WHERE created_at BETWEEN ? AND ?;

                SELECT * FROM appointments
                WHERE appointment_date BETWEEN ? AND ?;

                SELECT * FROM medical_report
                WHERE report_date BETWEEN ? AND ?;
            `;

            const [results] = await connection.query(sql, [
                startDate, endDate,
                startDate, endDate,
                startDate, endDate
            ]);

            patients = results[0];
            appointments = results[1];
            medicalReports = results[2];
        } else {
            const [allPatients] = await connection.query("SELECT * FROM patients");
            const [allAppointments] = await connection.query("SELECT * FROM appointments");
            const [allMedicalReports] = await connection.query("SELECT * FROM medical_report");

            patients = allPatients;
            appointments = allAppointments;
            medicalReports = allMedicalReports;
        }

        const totalPatients = patients.length;
        const totalAppointments = appointments.length;
        const totalMedicalReports = medicalReports.length;

        const appointmentsByStatus = {};
        appointments.forEach(apt => {
            appointmentsByStatus[apt.status] = (appointmentsByStatus[apt.status] || 0) + 1;
        });

        return res.status(200).json({
            totalPatients,
            totalAppointments,
            totalMedicalReports,
            appointmentsByStatus,
            patients,
            appointments,
            medicalReports
        });

    } catch (error) {
        console.error(error);

        return res.status(500).json({
            message: "Internal Server Error"
        });
    }
});

export default reportRouter;