const express = require('express');
const router = express.Router();
const UserController = require('../controllers/user.controller');
const { authenticateToken } = require('../middleware/auth');
const { requireSuperAdmin, requireAdmin, canViewOnboarding } = require('../middleware/roleCheck');

// All user routes require authentication
router.use(authenticateToken);

// Get all roles (Super Admin and Admin can view)
router.get('/roles', requireAdmin, UserController.getAllRoles);

// Audit log routes (Super Admin and Admin can view) - MUST BE BEFORE /:id route
router.get('/audit-logs', requireAdmin, UserController.getAuditLogs);
router.get('/audit-logs/user/:userId', requireAdmin, UserController.getAuditLogsByUser);
router.get('/audit-logs/entity/:type/:id', requireAdmin, UserController.getAuditLogsByEntity);

// User management routes (Admin can manage; Onboarding roles can read for dropdowns)
router.get('/', canViewOnboarding, UserController.getAllUsers);
router.get('/export/csv', requireAdmin, UserController.exportCsv);
router.get('/:id/full', requireAdmin, UserController.getUserFull);
router.post('/:id/reset-entra', requireAdmin, UserController.resetPasswordEntra);
router.get('/:id', requireAdmin, UserController.getUserById);

// Azure AD group import (Super Admin only) - MUST be before /:id routes
router.get('/import/azure/groups', requireSuperAdmin, UserController.getAzureGroupsList);
router.post('/import/azure', requireSuperAdmin, UserController.importFromAzure);

// User modification routes (Super Admin only)
router.post('/', requireSuperAdmin, UserController.createUser);
router.put('/:id', requireSuperAdmin, UserController.updateUser);
router.delete('/:id', requireSuperAdmin, UserController.deleteUser);
router.put('/:id/role', requireSuperAdmin, UserController.assignRole);
router.put('/:id/activate', requireSuperAdmin, UserController.toggleUserStatus);

module.exports = router;
