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

const router = express.Router();

const appointmentSelect = `
  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
`;

router.use(authenticate);

router.get('/', async (req, res) => {
  try {
    let query = appointmentSelect;
    const params = [];

    if (req.user.role === 'doctor') {
      query += ' WHERE a.doctor_id = ?';
      params.push(req.user.id);
    }

    query += ' ORDER BY a.appointment_date DESC, a.appointment_time DESC';

    const [appointments] = await pool.query(query, params);
    res.json(appointments);
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: 'Failed to fetch appointments.' });
  }
});

router.get('/assigned', authorize('doctor'), async (req, res) => {
  try {
    const [appointments] = await pool.query(
      `${appointmentSelect}
       WHERE a.doctor_id = ? AND a.status = 'scheduled'
       ORDER BY a.appointment_date ASC, a.appointment_time ASC`,
      [req.user.id]
    );
    res.json(appointments);
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: 'Failed to fetch assigned appointments.' });
  }
});

router.post('/', authorize('receptionist'), async (req, res) => {
  try {
    const { patient_id, doctor_id, appointment_date, appointment_time, status } =
      req.body;

    if (!patient_id || !doctor_id || !appointment_date || !appointment_time) {
      return res.status(400).json({ message: 'Required appointment fields missing.' });
    }

    const [result] = await pool.query(
      `INSERT INTO appointments (patient_id, doctor_id, appointment_date, appointment_time, status)
       VALUES (?, ?, ?, ?, ?)`,
      [
        patient_id,
        doctor_id,
        appointment_date,
        appointment_time,
        status || 'scheduled',
      ]
    );

    const [appointment] = await pool.query(
      `${appointmentSelect} WHERE a.id = ?`,
      [result.insertId]
    );
    res.status(201).json(appointment[0]);
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: 'Failed to create appointment.' });
  }
});

router.put('/:id', authorize('receptionist'), async (req, res) => {
  try {
    const { patient_id, doctor_id, appointment_date, appointment_time, status } =
      req.body;

    const [existing] = await pool.query('SELECT id FROM appointments WHERE id = ?', [
      req.params.id,
    ]);
    if (existing.length === 0) {
      return res.status(404).json({ message: 'Appointment not found.' });
    }

    await pool.query(
      `UPDATE appointments SET patient_id = ?, doctor_id = ?, appointment_date = ?,
       appointment_time = ?, status = ? WHERE id = ?`,
      [
        patient_id,
        doctor_id,
        appointment_date,
        appointment_time,
        status,
        req.params.id,
      ]
    );

    const [appointment] = await pool.query(
      `${appointmentSelect} WHERE a.id = ?`,
      [req.params.id]
    );
    res.json(appointment[0]);
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: 'Failed to update appointment.' });
  }
});

router.patch('/:id/cancel', authorize('receptionist'), async (req, res) => {
  try {
    const [result] = await pool.query(
      "UPDATE appointments SET status = 'cancelled' WHERE id = ?",
      [req.params.id]
    );
    if (result.affectedRows === 0) {
      return res.status(404).json({ message: 'Appointment not found.' });
    }

    const [appointment] = await pool.query(
      `${appointmentSelect} WHERE a.id = ?`,
      [req.params.id]
    );
    res.json(appointment[0]);
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: 'Failed to cancel appointment.' });
  }
});

router.delete('/:id', authorize('receptionist'), async (req, res) => {
  try {
    const [result] = await pool.query('DELETE FROM appointments WHERE id = ?', [
      req.params.id,
    ]);
    if (result.affectedRows === 0) {
      return res.status(404).json({ message: 'Appointment not found.' });
    }
    res.json({ message: 'Appointment deleted successfully.' });
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: 'Failed to delete appointment.' });
  }
});

module.exports = router;
