import { Router } from 'express';
import { productsController } from './products.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);

// ========== CATEGORIES (must be before :id routes) ==========
// List categories
router.get('/categories', (req, res, next) => productsController.findAllCategories(req, res, next));

// Get category by ID
router.get('/categories/:id', (req, res, next) => productsController.findCategoryById(req, res, next));

// Create category
router.post('/categories', requireAccess({ roles: ['admin', 'manager'], permission: 'categories:create' }), (req, res, next) =>
  productsController.createCategory(req, res, next)
);

// Update category
router.patch('/categories/:id', requireAccess({ roles: ['admin', 'manager'], permission: 'categories:update' }), (req, res, next) =>
  productsController.updateCategory(req, res, next)
);

// Delete category
router.delete('/categories/:id', requireAccess({ roles: ['admin'], permission: 'categories:delete' }), (req, res, next) =>
  productsController.deleteCategory(req, res, next)
);

// ========== CONVENIENCE ROUTES ==========
// Get sellable products
router.get('/sellable', (req, res, next) => productsController.getSellable(req, res, next));

// Get purchasable products
router.get('/purchasable', (req, res, next) => productsController.getPurchasable(req, res, next));

// Get product by SKU
router.get('/sku/:sku', (req, res, next) => productsController.findBySku(req, res, next));

// Get product by Barcode
router.get('/barcode/:barcode', (req, res, next) => productsController.findByBarcode(req, res, next));

// ========== PRODUCTS ==========
// List products
router.get('/', (req, res, next) => productsController.findAll(req, res, next));

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

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

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

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

export default router;
