import { Router } from 'express';
import { warehousesController } from './warehouses.controller.js';
import { authenticate } from '../../shared/middleware/auth.middleware.js';
import { requireAccess } from '../../shared/middleware/rbac.middleware.js';

const router = Router();

// All routes require authentication
router.use(authenticate);

// ========== LOCATIONS (before :id routes to avoid conflicts) ==========
// List all locations
router.get('/locations', (req, res, next) => warehousesController.findAllLocations(req, res, next));

// Get location by ID
router.get('/locations/:id', (req, res, next) => warehousesController.findLocationById(req, res, next));

// Create location
router.post('/locations', requireAccess({ roles: ['admin', 'manager', 'warehouse'], permission: 'locations:create' }), (req, res, next) =>
  warehousesController.createLocation(req, res, next)
);

// Update location
router.patch('/locations/:id', requireAccess({ roles: ['admin', 'manager', 'warehouse'], permission: 'locations:update' }), (req, res, next) =>
  warehousesController.updateLocation(req, res, next)
);

// Delete location
router.delete('/locations/:id', requireAccess({ roles: ['admin'], permission: 'locations:delete' }), (req, res, next) =>
  warehousesController.deleteLocation(req, res, next)
);

// ========== CONVENIENCE ROUTES ==========
// Get default warehouse
router.get('/default', (req, res, next) => warehousesController.getDefault(req, res, next));

// Get active warehouses
router.get('/active', (req, res, next) => warehousesController.getActive(req, res, next));

// Get warehouse by code
router.get('/code/:code', (req, res, next) => warehousesController.findByCode(req, res, next));

// Get locations for a specific warehouse
router.get('/:warehouseId/locations', (req, res, next) => warehousesController.getWarehouseLocations(req, res, next));

// ========== WAREHOUSES ==========
// List warehouses
router.get('/', (req, res, next) => warehousesController.findAll(req, res, next));

// Get warehouse by ID
router.get('/:id', (req, res, next) => warehousesController.findById(req, res, next));

// Create warehouse
router.post('/', requireAccess({ roles: ['admin', 'manager'], permission: 'warehouses:create' }), (req, res, next) =>
  warehousesController.create(req, res, next)
);

// Update warehouse
router.patch('/:id', requireAccess({ roles: ['admin', 'manager'], permission: 'warehouses:update' }), (req, res, next) =>
  warehousesController.update(req, res, next)
);

// Delete warehouse
router.delete('/:id', requireAccess({ roles: ['admin'], permission: 'warehouses:delete' }), (req, res, next) =>
  warehousesController.delete(req, res, next)
);

export default router;
