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

function formatReport(row) {
  return {
    id: row.id,
    appointmentId: row.appointment_id,
    patientId: row.patient_id,
    doctorId: row.doctor_id,
    patientName: row.patient_name,
    doctorName: row.doctor_name,
    diagnosis: row.diagnosis,
    prescription: row.prescription,
    reportDate: row.report_date,
    createdAt: row.created_at,
  };
}

const reportSelect = `
  SELECT mr.*,
    p.full_name AS patient_name,
    u.name AS doctor_name
  FROM medical_reports mr
  JOIN patients p ON p.id = mr.patient_id
  JOIN users u ON u.id = mr.doctor_id
`;

exports.getMedicalReports = async (req, res) => {
  try {
    const pool = getPool();
    let query = `${reportSelect}`;
    const params = [];

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

    query += ' ORDER BY mr.report_date DESC';

    const [rows] = await pool.query(query, params);
    res.json({ reports: rows.map(formatReport) });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};

exports.createMedicalReport = async (req, res) => {
  try {
    const { appointmentId, diagnosis, prescription, reportDate } = req.body;

    if (!appointmentId || !diagnosis || !prescription) {
      return res.status(400).json({ message: 'Appointment, diagnosis, and prescription are required' });
    }

    const pool = getPool();
    const [appointments] = await pool.query(
      'SELECT * FROM appointments WHERE id = ?',
      [appointmentId],
    );

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

    const appointment = appointments[0];

    if (req.user.role === 'doctor' && appointment.doctor_id !== req.user.id) {
      return res.status(403).json({ message: 'You can only report on your assigned appointments' });
    }

    if (appointment.status === 'cancelled') {
      return res.status(400).json({ message: 'Cannot create report for cancelled appointment' });
    }

    const [existingReport] = await pool.query(
      'SELECT id FROM medical_reports WHERE appointment_id = ?',
      [appointmentId],
    );
    if (existingReport.length) {
      return res.status(409).json({ message: 'Medical report already exists for this appointment' });
    }

    const finalReportDate = reportDate || new Date().toISOString().slice(0, 10);

    const [result] = await pool.query(
      `INSERT INTO medical_reports (appointment_id, patient_id, doctor_id, diagnosis, prescription, report_date)
       VALUES (?, ?, ?, ?, ?, ?)`,
      [
        appointmentId,
        appointment.patient_id,
        appointment.doctor_id,
        diagnosis,
        prescription,
        finalReportDate,
      ],
    );

    await pool.query("UPDATE appointments SET status = 'completed' WHERE id = ?", [appointmentId]);

    const [rows] = await pool.query(`${reportSelect} WHERE mr.id = ?`, [result.insertId]);
    res.status(201).json({ report: formatReport(rows[0]) });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};
