const express = require("express");
const router = express.Router();

const {
  listPatients,
  showCreatePatient,
  createPatient,
  showEditPatient,
  updatePatient,
  showPatientMedications,
  moveToWaitingRoom,
  showWaitingRoom,
  showPatientOverview,
  addPatientNote,
  callFromWaitingRoom,
  dischargePatient,
  showMedicationPlan,
  movePatientToWaitingRoom,
  deactivatePatient,
  activatePatient,
  showPatientOverviewDashborad,
  assignMedicationToPatient,
} = require("../controllers/patient.controller");

// ✅ WICHTIG: middleware export ist ein Object → destructuring!
const { requireLogin } = require("../middleware/auth.middleware");

/* =========================================
   ✅ PATIENT SELECT (Radiobutton -> Session)
========================================= */
router.post("/select", requireLogin, (req, res) => {
  try {
    const patientId = req.body.patientId;

    if (!patientId) {
      req.session.selectedPatientId = null;
      return res.json({ ok: true, selectedPatientId: null });
    }

    req.session.selectedPatientId = parseInt(patientId, 10);

    return res.json({
      ok: true,
      selectedPatientId: req.session.selectedPatientId,
    });
  } catch (err) {
    console.error("❌ Fehler /patients/select:", err);
    return res.status(500).json({ ok: false });
  }
});

/* =========================================
   ✅ PATIENT ROUTES
========================================= */
router.get("/", requireLogin, listPatients);

router.get("/create", requireLogin, showCreatePatient);
router.post("/create", requireLogin, createPatient);

router.get("/waiting-room", requireLogin, showWaitingRoom);

router.post("/waiting-room/:id", requireLogin, moveToWaitingRoom);
router.post(
  "/:id/back-to-waiting-room",
  requireLogin,
  movePatientToWaitingRoom,
);

router.get("/edit/:id", requireLogin, showEditPatient);
router.post("/update/:id", requireLogin, updatePatient);

router.get("/:id/medications", requireLogin, showPatientMedications);
router.post("/:id/medications", requireLogin, assignMedicationToPatient);

router.get("/:id/overview", requireLogin, showPatientOverview);
router.post("/:id/notes", requireLogin, addPatientNote);

router.get("/:id/plan", requireLogin, showMedicationPlan);

router.post("/:id/call", requireLogin, callFromWaitingRoom);
router.post("/:id/discharge", requireLogin, dischargePatient);

router.post("/deactivate/:id", requireLogin, deactivatePatient);
router.post("/activate/:id", requireLogin, activatePatient);

// ✅ Patient Dashboard
router.get("/:id", requireLogin, showPatientOverviewDashborad);

module.exports = router;
