const express = require('express');
const router = express.Router();
const pharmacistController = require('../controllers/pharmacistController');
const storeController = require('../controllers/storesController');
const { auth: protect, authorize } = require('../middleware/auth');
const multer = require('multer');
const path = require('path');
const fs = require('fs').promises;

// Ensure uploads directory exists
const uploadsDir = path.join(__dirname, '../uploads/pharmacists');
(async () => {
  try {
    await fs.mkdir(uploadsDir, { recursive: true });
    console.log(`Uploads directory created at: ${uploadsDir}`);
  } catch (err) {
    if (err.code !== 'EEXIST') {
      console.error('Error creating uploads directory:', err);
    }
  }
})();

// Configure multer for file uploads
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, uploadsDir);
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, 'pharmacist-' + uniqueSuffix + path.extname(file.originalname));
  }
});

const fileFilter = (req, file, cb) => {
  if (file.mimetype.startsWith('image/')) {
    cb(null, true);
  } else {
    cb(new Error('Only image files are allowed!'), false);
  }
};

const upload = multer({
  storage: storage,
  limits: {
    fileSize: 5 * 1024 * 1024 // 5MB limit
  },
  fileFilter: fileFilter
});

// Get all pharmacists with pagination and search
router.get('/', protect, pharmacistController.getAllPharmacists);

// Get pharmacist by ID
router.get('/:id', protect, pharmacistController.getPharmacistById);

// Create a new pharmacist
router.post('/', protect, upload.single('image'), pharmacistController.createPharmacist);

// Update a pharmacist
router.put('/:id', protect, upload.single('image'), pharmacistController.updatePharmacist);

// Delete a pharmacist
router.delete('/:id', protect, pharmacistController.deletePharmacist);

// Get pharmacist statistics
router.get('/stats/overview', protect, pharmacistController.getPharmacistStatistics);

// Get orders requiring prescription verification
router.get('/prescriptions/orders', protect, pharmacistController.getPrescriptionOrders);

// Verify/Reject prescription for an order
router.post('/prescriptions/orders/:orderId/verify', protect, pharmacistController.verifyPrescription);

// Store Assignment Routes
// Assign stores to pharmacist (Admin only)
router.post(
  '/:id/assign-stores',
  protect,
  authorize('admin'),
  pharmacistController.assignStores
);

// Get pharmacist's assigned stores
router.get(
  '/:id/assigned-stores',
  protect,
  authorize('admin', 'pharmacist'),
  pharmacistController.getAssignedStores
);

// Get available stores for assignment (excluding already assigned ones)
router.get(
  '/:id/available-stores',
  protect,
  authorize('admin'),
  storeController.getAvailableStoresForPharmacist
);

module.exports = router;