const express = require('express');
const router = express.Router();
const { auth, authorize } = require('../middleware/auth');
const {
  handleUpload,
  uploadPrescription,
  getMyPrescriptions,
  getPrescriptionById,
  getPrescriptionsByStatus,
  updatePrescriptionStatus,
  deletePrescription
} = require('../controllers/prescriptionsController');

// @route   POST /api/v1/prescriptions/upload
// @desc    Upload a new prescription
// @access  Private
router.post('/upload', 
  auth, 
  handleUpload, 
  uploadPrescription
);

// @route   POST /api/v1/prescriptions/
// @desc    Upload a new prescription (legacy endpoint)
// @access  Private
router.post('/', 
  auth, 
  handleUpload, 
  uploadPrescription
);

// @route   GET /api/prescriptions/my-prescriptions
// @desc    Get current user's prescriptions
// @access  Private
router.get('/my-prescriptions', auth, getMyPrescriptions);

// @route   GET /api/prescriptions/status
// @desc    Get prescriptions by status (pending/approved/rejected)
// @access  Private (Admin/Pharmacist)
router.get(
  '/status',
  auth,
  authorize('admin', 'pharmacist'),
  getPrescriptionsByStatus
);

// Legacy endpoint for backward compatibility
router.get(
  '/pending', 
  auth, 
  authorize('admin', 'pharmacist'), 
  (req, res) => {
    // Redirect to the new endpoint with status=pending
    req.query.status = 'pending';
    return getPrescriptionsByStatus(req, res);
  }
);

// @route   GET /api/prescriptions/:id
// @desc    Get prescription by ID
// @access  Private
router.get('/:id', auth, getPrescriptionById);

// @route   PUT /api/prescriptions/:id/status
// @desc    Update prescription status (Approve/Reject)
// @access  Private (Admin/Pharmacist)
router.put(
  '/:id/status', 
  auth, 
  authorize('admin', 'pharmacist'), 
  updatePrescriptionStatus
);

// @route   DELETE /api/prescriptions/:id
// @desc    Delete a prescription (Admin only)
// @access  Private (Admin)
router.delete(
  '/:id', 
  auth, 
  authorize('admin'), 
  deletePrescription
);

module.exports = router;
