const express = require('express');
const Appointment = require('../models/Appointment');
const { protect } = require('../middleware/auth');

const router = express.Router();

// @route   GET /api/appointments
// @desc    Get all appointments
// @access  Private
router.get('/', protect, async (req, res) => {
  try {
    const appointments = await Appointment.find()
      .populate('patient', 'name phone email')
      .populate('doctor', 'name specialty')
      .sort({ date: -1, time: -1 });
    res.json(appointments);
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Server error' });
  }
});

// @route   GET /api/appointments/:id
// @desc    Get single appointment
// @access  Private
router.get('/:id', protect, async (req, res) => {
  try {
    const appointment = await Appointment.findById(req.params.id)
      .populate('patient', 'name phone email')
      .populate('doctor', 'name specialty');
    
    if (!appointment) {
      return res.status(404).json({ message: 'Appointment not found' });
    }
    res.json(appointment);
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Server error' });
  }
});

// @route   POST /api/appointments
// @desc    Create an appointment
// @access  Private
router.post('/', protect, async (req, res) => {
  try {
    const { patient, doctor, date, time, status, notes } = req.body;

    const appointment = await Appointment.create({
      patient,
      doctor,
      date,
      time,
      status: status || 'scheduled',
      notes
    });

    const populatedAppointment = await Appointment.findById(appointment._id)
      .populate('patient', 'name phone email')
      .populate('doctor', 'name specialty');

    res.status(201).json(populatedAppointment);
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Server error' });
  }
});

// @route   PUT /api/appointments/:id
// @desc    Update an appointment
// @access  Private
router.put('/:id', protect, async (req, res) => {
  try {
    const { patient, doctor, date, time, status, notes } = req.body;

    const appointment = await Appointment.findById(req.params.id);
    if (!appointment) {
      return res.status(404).json({ message: 'Appointment not found' });
    }

    appointment.patient = patient || appointment.patient;
    appointment.doctor = doctor || appointment.doctor;
    appointment.date = date || appointment.date;
    appointment.time = time || appointment.time;
    appointment.status = status || appointment.status;
    appointment.notes = notes || appointment.notes;

    const updatedAppointment = await appointment.save();
    const populatedAppointment = await Appointment.findById(updatedAppointment._id)
      .populate('patient', 'name phone email')
      .populate('doctor', 'name specialty');

    res.json(populatedAppointment);
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Server error' });
  }
});

// @route   DELETE /api/appointments/:id
// @desc    Delete an appointment
// @access  Private
router.delete('/:id', protect, async (req, res) => {
  try {
    const appointment = await Appointment.findById(req.params.id);
    if (!appointment) {
      return res.status(404).json({ message: 'Appointment not found' });
    }

    await appointment.deleteOne();
    res.json({ message: 'Appointment deleted successfully' });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Server error' });
  }
});

// @route   GET /api/appointments/filter/:status
// @desc    Get appointments by status
// @access  Private
router.get('/filter/:status', protect, async (req, res) => {
  try {
    const appointments = await Appointment.find({ status: req.params.status })
      .populate('patient', 'name phone email')
      .populate('doctor', 'name specialty')
      .sort({ date: -1 });
    res.json(appointments);
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: 'Server error' });
  }
});

module.exports = router;
