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

function formatPatient(row) {
  return {
    id: row.id,
    fullName: row.full_name,
    gender: row.gender,
    dateOfBirth: row.date_of_birth,
    phone: row.phone,
    address: row.address,
    createdAt: row.created_at,
  };
}

exports.getPatients = async (req, res) => {
  try {
    const pool = getPool();
    const [rows] = await pool.query('SELECT * FROM patients ORDER BY full_name');
    res.json({ patients: rows.map(formatPatient) });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};

exports.getPatient = async (req, res) => {
  try {
    const pool = getPool();
    const [rows] = await pool.query('SELECT * FROM patients WHERE id = ?', [req.params.id]);

    if (!rows.length) {
      return res.status(404).json({ message: 'Patient not found' });
    }

    res.json({ patient: formatPatient(rows[0]) });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};

exports.createPatient = async (req, res) => {
  try {
    const { fullName, gender, dateOfBirth, phone, address } = req.body;

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

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

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

exports.updatePatient = async (req, res) => {
  try {
    const { fullName, gender, dateOfBirth, phone, address } = req.body;
    const pool = getPool();

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

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

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

exports.deletePatient = async (req, res) => {
  try {
    const pool = getPool();
    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' });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};
