// controllers/consultation.controller.js
const db = require("../../../managers/dbConfig");

const addToQueue = async (req, res, next) => {
  try {
    const { patient_id, session_id, department, logged_by } = req.body;

    if (!patient_id || !session_id || !logged_by) {
      throw "patient_id, session_id and Staff identity are required";
    }

    // Avoid duplicate queue entry for same session
    const [existing] = await db.execute(
      `SELECT id FROM consultation_queue WHERE patient_id = ? AND status = 'waiting'`,
      [patient_id]
    );
    //console.log(existing);

    if (existing.length > 0) throw new Error("Patient already on queue");

    await db.execute(
      `INSERT INTO consultation_queue (patient_id, session_id, department, logged_by)
       VALUES (?, ?, ?, ?)`,
      [patient_id, session_id, department || null, logged_by]
    );

    res.status(201).json({
      status: "success",
      message: "Patient added to queue",
    });
  } catch (error) {
    next(error);
  }
};

const updateQueueStatus = async (req, res, next) => {
  const { patient_id, session_id, status, doctor_name } = req.body;

  if (!patient_id || !session_id || !status || !doctor_name)
    throw new Error("All fields are required");

  const validStatuses = ["waiting", "attended", "skipped"];
  if (!validStatuses.includes(status)) {
    throw "Invalid status value";
  }

  const sql = `
    UPDATE consultation_queue
    SET status = ?, attended_by = ?, attended_at = CURRENT_TIMESTAMP
    WHERE patient_id = ? AND session_id = ?
  `;

  try {
    const [result] = await db.execute(sql, [
      status,
      doctor_name,
      patient_id,
      session_id,
    ]);

    if (result.affectedRows === 0) throw "No matching queue entry found";

    res.json({ message: "Queue status updated successfully" });
  } catch (error) {
    logger.error("Update queue error:", error);
    next(error);
  }
};

const getCurrentQueue = async (req, res, next) => {
  try {
    const [queue] = await db.execute(
      `SELECT q.*, p.firstName, p.lastName, p.age
       FROM consultation_queue q
       JOIN patients p ON p.patient_id = q.patient_id
       WHERE q.status = 'waiting'
       ORDER BY q.date_time ASC`
    );

    res.status(200).json({
      status: "success",
      data: queue,
    });
  } catch (error) {
    next(error);
  }
};

module.exports = { addToQueue, getCurrentQueue, updateQueueStatus };
