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

const router = express.Router();

router.use(authenticate);
router.use(authorize('receptionist'));

router.get('/', async (req, res) => {
  try {
    const [patients] = await pool.query(
      'SELECT * FROM patients ORDER BY full_name ASC'
    );
    res.json(patients);
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: 'Failed to fetch patients.' });
  }
});

router.get('/:id', async (req, res) => {
  try {
    const [patients] = await pool.query('SELECT * FROM patients WHERE id = ?', [
      req.params.id,
    ]);
    if (patients.length === 0) {
      return res.status(404).json({ message: 'Patient not found.' });
    }
    res.json(patients[0]);
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: 'Failed to fetch patient.' });
  }
});

router.post('/', async (req, res) => {
  try {
    const { full_name, gender, date_of_birth, phone_number, address } = req.body;

    if (!full_name || !gender || !date_of_birth || !phone_number || !address) {
      return res.status(400).json({ message: 'All patient fields are required.' });
    }

    const [result] = await pool.query(
      `INSERT INTO patients (full_name, gender, date_of_birth, phone_number, address)
       VALUES (?, ?, ?, ?, ?)`,
      [full_name, gender, date_of_birth, phone_number, address]
    );

    const [patient] = await pool.query('SELECT * FROM patients WHERE id = ?', [
      result.insertId,
    ]);
    res.status(201).json(patient[0]);
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: 'Failed to create patient.' });
  }
});

router.put('/:id', async (req, res) => {
  try {
    const { full_name, gender, date_of_birth, phone_number, address } = req.body;

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

    await pool.query(
      `UPDATE patients SET full_name = ?, gender = ?, date_of_birth = ?,
       phone_number = ?, address = ? WHERE id = ?`,
      [full_name, gender, date_of_birth, phone_number, address, req.params.id]
    );

    const [patient] = await pool.query('SELECT * FROM patients WHERE id = ?', [
      req.params.id,
    ]);
    res.json(patient[0]);
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: 'Failed to update patient.' });
  }
});

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

module.exports = router;
