import { Router } from 'express';
import personalEquipmentController from '../controllers/personalEquipment.controller';
import { authenticate } from '../middleware/auth.middleware';
import { requirePermission, requireAnyPermission } from '../middleware/rbac.middleware';
import { permissionService } from '../services/permission.service';

const router = Router();

// Own items — any authenticated user with view permission
router.get('/my', authenticate, personalEquipmentController.getMy.bind(personalEquipmentController));

// All items — requires view_all or create
router.get('/', authenticate, requireAnyPermission('persoenliche_ausruestung:view_all', 'persoenliche_ausruestung:create'), personalEquipmentController.list.bind(personalEquipmentController));

// By user — own data or view_all
router.get('/user/:userId', authenticate, async (req, res, next) => {
  const isOwn = req.user!.id === req.params.userId;
  if (isOwn) {
    const hasView = await permissionService.hasPermission(req.user!.groups ?? [], 'persoenliche_ausruestung:view');
    if (hasView || req.user!.groups?.includes('dashboard_admin')) return next();
  }
  const hasViewAll = await permissionService.hasPermission(req.user!.groups ?? [], 'persoenliche_ausruestung:view_all');
  if (hasViewAll || req.user!.groups?.includes('dashboard_admin')) return next();
  res.status(403).json({ success: false, message: 'Keine Berechtigung' });
}, personalEquipmentController.getByUser.bind(personalEquipmentController));

// Zustand options — GET (all authenticated users), PUT (admin:write)
router.get('/zustand-options', authenticate, personalEquipmentController.getZustandOptions.bind(personalEquipmentController));
router.put('/zustand-options', authenticate, requirePermission('admin:write'), personalEquipmentController.updateZustandOptions.bind(personalEquipmentController));

// Single item
router.get('/:id', authenticate, personalEquipmentController.getById.bind(personalEquipmentController));

// Create
router.post('/', authenticate, requirePermission('persoenliche_ausruestung:create'), personalEquipmentController.create.bind(personalEquipmentController));

// Update
router.patch('/:id', authenticate, requirePermission('persoenliche_ausruestung:edit'), personalEquipmentController.update.bind(personalEquipmentController));

// Delete (soft)
router.delete('/:id', authenticate, requirePermission('persoenliche_ausruestung:delete'), personalEquipmentController.delete.bind(personalEquipmentController));

export default router;
