const { getPool } = require('../config/db');

exports.generateReport = async (req, res) => {
  try {
    const { startDate, endDate } = req.query;

    if (!startDate || !endDate) {
      return res.status(400).json({ message: 'Start date and end date are required' });
    }

    const pool = getPool();

    const [appointments] = await pool.query(
      `SELECT a.id, a.appointment_date, a.appointment_time, a.status,
        p.full_name AS patient_name,
        u.name AS doctor_name
       FROM appointments a
       JOIN patients p ON p.id = a.patient_id
       JOIN users u ON u.id = a.doctor_id
       WHERE a.appointment_date BETWEEN ? AND ?
       ORDER BY a.appointment_date, a.appointment_time`,
      [startDate, endDate],
    );

    const [stats] = await pool.query(
      `SELECT
        COUNT(*) AS totalAppointments,
        SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) AS totalCompleted,
        SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) AS totalCancelled
       FROM appointments
       WHERE appointment_date BETWEEN ? AND ?`,
      [startDate, endDate],
    );

    const [attended] = await pool.query(
      `SELECT DISTINCT p.id, p.full_name AS patient_name, p.phone
       FROM appointments a
       JOIN patients p ON p.id = a.patient_id
       WHERE a.status = 'completed' AND a.appointment_date BETWEEN ? AND ?
       ORDER BY p.full_name`,
      [startDate, endDate],
    );

    const [medicalReports] = await pool.query(
      `SELECT mr.id, mr.diagnosis, mr.prescription, mr.report_date,
        p.full_name AS patient_name,
        u.name AS doctor_name
       FROM medical_reports mr
       JOIN patients p ON p.id = mr.patient_id
       JOIN users u ON u.id = mr.doctor_id
       WHERE mr.report_date BETWEEN ? AND ?
       ORDER BY mr.report_date DESC`,
      [startDate, endDate],
    );

    res.json({
      startDate,
      endDate,
      summary: {
        totalAppointments: Number(stats[0].totalAppointments),
        totalCompleted: Number(stats[0].totalCompleted),
        totalCancelled: Number(stats[0].totalCancelled),
        patientsAttended: attended.length,
      },
      appointments,
      patientsAttended: attended,
      medicalReports,
    });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};
