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

const router = express.Router();

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

router.use(authenticate);

router.get('/', async (req, res) => {
  try {
    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 [reports] = await pool.query(query, params);
    res.json(reports);
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: 'Failed to fetch medical reports.' });
  }
});

router.post('/', authorize('doctor'), async (req, res) => {
  try {
    const { appointment_id, diagnosis, prescription, report_date } = req.body;

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

    const [appointments] = await pool.query(
      'SELECT * FROM appointments WHERE id = ? AND doctor_id = ?',
      [appointment_id, req.user.id]
    );

    if (appointments.length === 0) {
      return res.status(404).json({ message: 'Appointment not found or not assigned to you.' });
    }

    const appointment = appointments[0];

    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 = ?',
      [appointment_id]
    );
    if (existingReport.length > 0) {
      return res.status(400).json({ message: 'Medical report already exists for this appointment.' });
    }

    const date = report_date || new Date().toISOString().split('T')[0];

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

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

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

router.put('/:id', authorize('doctor'), async (req, res) => {
  try {
    const { diagnosis, prescription, report_date } = req.body;

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

    await pool.query(
      'UPDATE medical_reports SET diagnosis = ?, prescription = ?, report_date = ? WHERE id = ?',
      [diagnosis, prescription, report_date, req.params.id]
    );

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

module.exports = router;
