const express = require('express');
const pool = require('../config/db');
const { authenticate } = require('../middleware/auth');

const router = express.Router();

router.use(authenticate);

router.get('/summary', async (req, res) => {
  try {
    const { start_date, end_date } = req.query;

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

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

    const [attendedPatients] = await pool.query(
      `SELECT DISTINCT p.id, p.full_name, p.gender, p.date_of_birth,
        p.phone_number, p.address, mr.report_date
       FROM medical_reports mr
       JOIN patients p ON mr.patient_id = p.id
       WHERE mr.report_date BETWEEN ? AND ?
       ORDER BY p.full_name`,
      [start_date, end_date]
    );

    const total = appointments.length;
    const completed = appointments.filter((a) => a.status === 'completed').length;
    const cancelled = appointments.filter((a) => a.status === 'cancelled').length;
    const scheduled = appointments.filter((a) => a.status === 'scheduled').length;

    res.json({
      start_date,
      end_date,
      total_appointments: total,
      total_completed: completed,
      total_cancelled: cancelled,
      total_scheduled: scheduled,
      patients_attended: attendedPatients,
      appointments,
    });
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: 'Failed to generate report.' });
  }
});

module.exports = router;
