/**
 * User Management Routes
 * Route definitions for user management endpoints
 */

// Import Express Router
const express = require('express');
// Create router instance
const router = express.Router();
// Import user controllers
const userControllers = require('../controllers');
// Import user validations
const {
  validateCreateUser,
  validateUpdateUser,
  validateGetUser,
  validateDeleteUser,
  validateListUsers,
} = require('../validations');
// Import authentication and authorization middlewares
const { authenticate, requireRole } = require('../../../middlewares/auth');

/**
 * @swagger
 * /users:
 *   get:
 *     summary: List users
 *     description: Get a paginated list of users with optional filters
 *     tags: [Users]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: query
 *         name: page
 *         schema:
 *           type: integer
 *           default: 1
 *         description: Page number
 *       - in: query
 *         name: limit
 *         schema:
 *           type: integer
 *           default: 10
 *         description: Number of users per page
 *       - in: query
 *         name: role
 *         schema:
 *           type: string
 *           enum: [cashier, manager, system_admin]
 *         description: Filter by role
 *       - in: query
 *         name: active
 *         schema:
 *           type: string
 *           enum: [true, false]
 *         description: Filter by active status
 *     responses:
 *       200:
 *         description: Users retrieved successfully
 *       401:
 *         description: Unauthorized
 */
router.get('/', authenticate, requireRole(['manager', 'system_admin']), validateListUsers, userControllers.listUsers);

/**
 * @swagger
 * /users/{id}:
 *   get:
 *     summary: Get user by ID
 *     description: Retrieve a specific user by ID
 *     tags: [Users]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
 *         description: User ID
 *     responses:
 *       200:
 *         description: User retrieved successfully
 *       404:
 *         description: User not found
 *       401:
 *         description: Unauthorized
 */
router.get('/:id', authenticate, validateGetUser, userControllers.getUserById);

/**
 * @swagger
 * /users:
 *   post:
 *     summary: Create new user
 *     description: Create a new user account (manager/admin only)
 *     tags: [Users]
 *     security:
 *       - bearerAuth: []
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required:
 *               - username
 *               - email
 *               - password
 *             properties:
 *               username:
 *                 type: string
 *                 example: newuser
 *               email:
 *                 type: string
 *                 format: email
 *                 example: user@example.com
 *               password:
 *                 type: string
 *                 format: password
 *                 example: password123
 *               full_name:
 *                 type: string
 *                 example: New User
 *               role:
 *                 type: string
 *                 enum: [cashier, manager, system_admin]
 *                 example: cashier
 *               pin_code:
 *                 type: string
 *                 example: "1234"
 *     responses:
 *       201:
 *         description: User created successfully
 *       400:
 *         description: Validation error
 *       401:
 *         description: Unauthorized
 *       403:
 *         description: Forbidden - Insufficient permissions
 */
router.post('/', authenticate, requireRole(['manager', 'system_admin']), validateCreateUser, userControllers.createUser);

/**
 * @swagger
 * /users/{id}:
 *   put:
 *     summary: Update user
 *     description: Update user information (users can update themselves, managers/admins can update anyone)
 *     tags: [Users]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
 *         description: User ID
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               username:
 *                 type: string
 *               email:
 *                 type: string
 *                 format: email
 *               password:
 *                 type: string
 *                 format: password
 *               full_name:
 *                 type: string
 *               role:
 *                 type: string
 *                 enum: [cashier, manager, system_admin]
 *               pin_code:
 *                 type: string
 *               active:
 *                 type: boolean
 *     responses:
 *       200:
 *         description: User updated successfully
 *       400:
 *         description: Validation error
 *       401:
 *         description: Unauthorized
 *       403:
 *         description: Forbidden - Insufficient permissions
 *       404:
 *         description: User not found
 */
// Middleware to check if user can update (self or manager/admin)
const canUpdateUser = (req, res, next) => {
  const targetUserId = parseInt(req.params.id);
  const currentUserId = req.user.id;
  const currentUserRole = req.user.role;
  
  // Users can update themselves, managers/admins can update anyone
  if (targetUserId === currentUserId || ['manager', 'system_admin'].includes(currentUserRole)) {
    return next();
  }
  
  return res.status(403).json({
    success: false,
    message: 'Forbidden - You can only update your own profile',
  });
};

router.put('/:id', authenticate, canUpdateUser, validateUpdateUser, userControllers.updateUser);

/**
 * @swagger
 * /users/{id}:
 *   delete:
 *     summary: Delete user
 *     description: Soft delete a user (manager/admin only)
 *     tags: [Users]
 *     security:
 *       - bearerAuth: []
 *     parameters:
 *       - in: path
 *         name: id
 *         required: true
 *         schema:
 *           type: integer
 *         description: User ID
 *     responses:
 *       200:
 *         description: User deleted successfully
 *       401:
 *         description: Unauthorized
 *       403:
 *         description: Forbidden - Insufficient permissions
 *       404:
 *         description: User not found
 */
router.delete('/:id', authenticate, requireRole(['manager', 'system_admin']), validateDeleteUser, userControllers.deleteUser);

// Export router
module.exports = router;

