import { Router } from 'express';

import { authenticate } from '../../middlewares/auth.middleware';
import { requirePermission } from '../../middlewares/rbac.middleware';

import { groupController } from './group';
import { organizationController } from './organization';
import { profileController } from './profile';
import { userManagementController } from './user';
import { verificationController } from './verification';

/**
 * EN: Create and configure Identity routes
 * VI: Tạo và cấu hình routes cho Identity
 */
export const createIdentityRouter = (): Router => {
    const router = Router();

    // =============================================================================
    // EN: User Management Endpoints
    // VI: Endpoints Quản Lý Người Dùng
    // =============================================================================

    /**
     * @swagger
     * /api/{version}/identity/users:
     *   get:
     *     summary: List users
     *     description: Retrieve a list of users with pagination and filtering
     *     tags: [Identity - Users]
     *     security:
     *       - bearerAuth: []
     *     parameters:
     *       - in: path
     *         name: version
     *         required: true
     *         schema:
     *           type: string
     *           default: v1
     *         description: API version
     *       - in: query
     *         name: page
     *         schema:
     *           type: integer
     *           default: 1
     *       - in: query
     *         name: limit
     *         schema:
     *           type: integer
     *           default: 10
     *       - in: query
     *         name: search
     *         schema:
     *           type: string
     *     responses:
     *       200:
     *         description: Users retrieved successfully
     *         content:
     *           application/json:
     *             schema:
     *               allOf:
     *                 - $ref: '#/components/schemas/ApiResponse'
     *                 - type: object
     *                   properties:
     *                     data:
     *                       type: array
     *                       items:
     *                         $ref: '#/components/schemas/User'
     *       401:
     *         description: Unauthorized
     *       403:
     *         description: Forbidden
     */
    router.get('/users', authenticate(), requirePermission('identity', 'read'), userManagementController.list.bind(userManagementController));

    /**
     * @swagger
     * /api/{version}/identity/users/{id}:
     *   get:
     *     summary: Get user details
     *     description: Retrieve detailed information about a specific user
     *     tags: [Identity - Users]
     *     security:
     *       - bearerAuth: []
     *     parameters:
     *       - in: path
     *         name: version
     *         required: true
     *         schema:
     *           type: string
     *           default: v1
     *         description: API version
     *       - in: path
     *         name: id
     *         required: true
     *         schema:
     *           type: string
     *         description: User ID
     *     responses:
     *       200:
     *         description: User retrieved successfully
     *         content:
     *           application/json:
     *             schema:
     *               allOf:
     *                 - $ref: '#/components/schemas/ApiResponse'
     *                 - type: object
     *                   properties:
     *                     data:
     *                       $ref: '#/components/schemas/User'
     *       404:
     *         description: User not found
     */
    router.get('/users/:id', authenticate(), requirePermission('identity', 'read'), userManagementController.get.bind(userManagementController));

    /**
     * @swagger
     * /api/{version}/identity/users/{id}:
     *   put:
     *     summary: Update user
     *     description: Update user information
     *     tags: [Identity - Users]
     *     security:
     *       - bearerAuth: []
     *     parameters:
     *       - in: path
     *         name: version
     *         required: true
     *         schema:
     *           type: string
     *           default: v1
     *         description: API version
     *       - in: path
     *         name: id
     *         required: true
     *         schema:
     *           type: string
     *         description: User ID
     *     requestBody:
     *       required: true
     *       content:
     *         application/json:
     *           schema:
     *             $ref: '#/components/schemas/UpdateUserRequest'
     *     responses:
     *       200:
     *         description: User updated successfully
     *         content:
     *           application/json:
     *             schema:
     *               allOf:
     *                 - $ref: '#/components/schemas/ApiResponse'
     *                 - type: object
     *                   properties:
     *                     data:
     *                       $ref: '#/components/schemas/User'
     */
    router.put('/users/:id', authenticate(), requirePermission('identity', 'update'), userManagementController.update.bind(userManagementController));

    /**
     * @swagger
     * /api/{version}/identity/users/{id}:
     *   delete:
     *     summary: Delete user
     *     description: Delete a user account (soft delete or hard delete depending on policy)
     *     tags: [Identity - Users]
     *     security:
     *       - bearerAuth: []
     *     parameters:
     *       - in: path
     *         name: version
     *         required: true
     *         schema:
     *           type: string
     *           default: v1
     *         description: API version
     *       - in: path
     *         name: id
     *         required: true
     *         schema:
     *           type: string
     *         description: User ID
     *     responses:
     *       200:
     *         description: User deleted successfully
     *         content:
     *           application/json:
     *             schema:
     *               $ref: '#/components/schemas/ApiResponse'
     */
    router.delete('/users/:id', authenticate(), requirePermission('identity', 'delete'), userManagementController.delete.bind(userManagementController));

    /**
     * @swagger
     * /api/{version}/identity/users/{id}/deactivate:
     *   post:
     *     summary: Deactivate user
     *     description: Deactivate a user account without deleting it
     *     tags: [Identity - Users]
     *     security:
     *       - bearerAuth: []
     *     parameters:
     *       - in: path
     *         name: version
     *         required: true
     *         schema:
     *           type: string
     *           default: v1
     *         description: API version
     *       - in: path
     *         name: id
     *         required: true
     *         schema:
     *           type: string
     *         description: User ID
     *     responses:
     *       200:
     *         description: User deactivated successfully
     *         content:
     *           application/json:
     *             schema:
     *               $ref: '#/components/schemas/ApiResponse'
     */
    router.post('/users/:id/deactivate', authenticate(), requirePermission('identity', 'update'), userManagementController.deactivate.bind(userManagementController));

    /**
     * @swagger
     * /api/{version}/identity/users/{id}/reactivate:
     *   post:
     *     summary: Reactivate user
     *     description: Reactivate a previously deactivated user account
     *     tags: [Identity - Users]
     *     security:
     *       - bearerAuth: []
     *     parameters:
     *       - in: path
     *         name: version
     *         required: true
     *         schema:
     *           type: string
     *           default: v1
     *         description: API version
     *       - in: path
     *         name: id
     *         required: true
     *         schema:
     *           type: string
     *         description: User ID
     *     responses:
     *       200:
     *         description: User reactivated successfully
     *         content:
     *           application/json:
     *             schema:
     *               $ref: '#/components/schemas/ApiResponse'
     */
    router.post('/users/:id/reactivate', authenticate(), requirePermission('identity', 'update'), userManagementController.reactivate.bind(userManagementController));

    /**
     * @swagger
     * /api/{version}/identity/users/bulk-import:
     *   post:
     *     summary: Bulk import users
     *     description: Import multiple users from a file or JSON payload
     *     tags: [Identity - Users]
     *     security:
     *       - bearerAuth: []
     *     parameters:
     *       - in: path
     *         name: version
     *         required: true
     *         schema:
     *           type: string
     *           default: v1
     *         description: API version
     *     requestBody:
     *       required: true
     *       content:
     *         application/json:
     *           schema:
     *             type: object
     *             required: [users]
     *             properties:
     *               users:
     *                 type: array
     *                 items:
     *                   $ref: '#/components/schemas/CreateUserRequest'
     *     responses:
     *       200:
     *         description: Users imported successfully
     *         content:
     *           application/json:
     *             schema:
     *               allOf:
     *                 - $ref: '#/components/schemas/ApiResponse'
     *                 - type: object
     *                   properties:
     *                     data:
     *                       type: object
     *                       properties:
     *                         imported:
     *                           type: integer
     *                         failed:
     *                           type: integer
     */
    router.post('/users/bulk-import', authenticate(), requirePermission('identity', 'create'), userManagementController.bulkImport.bind(userManagementController));

    /**
     * @swagger
     * /api/{version}/identity/users/bulk-export:
     *   get:
     *     summary: Bulk export users
     *     description: Export users to a file (CSV/JSON)
     *     tags: [Identity - Users]
     *     security:
     *       - bearerAuth: []
     *     parameters:
     *       - in: path
     *         name: version
     *         required: true
     *         schema:
     *           type: string
     *           default: v1
     *         description: API version
     *       - in: query
     *         name: format
     *         schema:
     *           type: string
     *           enum: [csv, json]
     *           default: json
     *     responses:
     *       200:
     *         description: Export successful
     *         content:
     *           application/json:
     *             schema:
     *               type: object // File download
     */
    router.get('/users/bulk-export', authenticate(), requirePermission('identity', 'read'), userManagementController.bulkExport.bind(userManagementController));

    // =============================================================================
    // EN: Profile Management Endpoints
    // VI: Endpoints Quản Lý Profile
    // =============================================================================

    /**
     * @swagger
     * /api/{version}/identity/users/{id}/profile:
     *   get:
     *     summary: Get user profile
     *     description: Get profile information for a specific user
     *     tags: [Identity - Profile]
     *     security:
     *       - bearerAuth: []
     *     parameters:
     *       - in: path
     *         name: version
     *         required: true
     *         schema:
     *           type: string
     *           default: v1
     *         description: API version
     *       - in: path
     *         name: id
     *         required: true
     *         schema:
     *           type: string
     *         description: User ID
     *     responses:
     *       200:
     *         description: Profile retrieved successfully
     *         content:
     *           application/json:
     *             schema:
     *               allOf:
     *                 - $ref: '#/components/schemas/ApiResponse'
     *                 - type: object
     *                   properties:
     *                     data:
     *                       $ref: '#/components/schemas/UserProfile'
     */
    router.get('/users/:id/profile', authenticate(), profileController.get.bind(profileController));

    /**
     * @swagger
     * /api/{version}/identity/users/{id}/profile:
     *   put:
     *     summary: Update user profile
     *     description: Update profile information for a specific user
     *     tags: [Identity - Profile]
     *     security:
     *       - bearerAuth: []
     *     parameters:
     *       - in: path
     *         name: version
     *         required: true
     *         schema:
     *           type: string
     *           default: v1
     *         description: API version
     *       - in: path
     *         name: id
     *         required: true
     *         schema:
     *           type: string
     *         description: User ID
     *     requestBody:
     *       required: true
     *       content:
     *         application/json:
     *           schema:
     *             $ref: '#/components/schemas/UpdateProfileRequest'
     *     responses:
     *       200:
     *         description: Profile updated successfully
     *         content:
     *           application/json:
     *             schema:
     *               allOf:
     *                 - $ref: '#/components/schemas/ApiResponse'
     *                 - type: object
     *                   properties:
     *                     data:
     *                       $ref: '#/components/schemas/UserProfile'
     */
    router.put('/users/:id/profile', authenticate(), profileController.update.bind(profileController));

    /**
     * @swagger
     * /api/{version}/identity/users/{id}/profile/avatar:
     *   post:
     *     summary: Upload avatar
     *     description: Upload a new avatar image for the user
     *     tags: [Identity - Profile]
     *     security:
     *       - bearerAuth: []
     *     parameters:
     *       - in: path
     *         name: version
     *         required: true
     *         schema:
     *           type: string
     *           default: v1
     *         description: API version
     *       - in: path
     *         name: id
     *         required: true
     *         schema:
     *           type: string
     *         description: User ID
     *     requestBody:
     *       content:
     *         multipart/form-data:
     *           schema:
     *             type: object
     *             properties:
     *               avatar:
     *                 type: string
     *                 format: binary
     *     responses:
     *       200:
     *         description: Avatar uploaded successfully
     *         content:
     *           application/json:
     *             schema:
     *               $ref: '#/components/schemas/ApiResponse'
     */
    router.post('/users/:id/profile/avatar', authenticate(), profileController.uploadAvatar.bind(profileController));

    /**
     * @swagger
     * /api/{version}/identity/users/{id}/profile/avatar:
     *   delete:
     *     summary: Delete avatar
     *     description: Remove the user's current avatar
     *     tags: [Identity - Profile]
     *     security:
     *       - bearerAuth: []
     *     parameters:
     *       - in: path
     *         name: version
     *         required: true
     *         schema:
     *           type: string
     *           default: v1
     *         description: API version
     *       - in: path
     *         name: id
     *         required: true
     *         schema:
     *           type: string
     *         description: User ID
     *     responses:
     *       200:
     *         description: Avatar deleted successfully
     *         content:
     *           application/json:
     *             schema:
     *               $ref: '#/components/schemas/ApiResponse'
     */
    router.delete('/users/:id/profile/avatar', authenticate(), profileController.deleteAvatar.bind(profileController));

    // =============================================================================
    // EN: Verification Endpoints
    // VI: Endpoints Xác Thực
    // =============================================================================

    /**
     * @swagger
     * /api/{version}/identity/verification/email/request:
     *   post:
     *     summary: Request email verification
     *     description: Send an email verification link/code to the user
     *     tags: [Identity - Verification]
     *     security:
     *       - bearerAuth: []
     *     parameters:
     *       - in: path
     *         name: version
     *         required: true
     *         schema:
     *           type: string
     *           default: v1
     *         description: API version
     *     responses:
     *       200:
     *         description: Verification email sent
     *         content:
     *           application/json:
     *             schema:
     *               $ref: '#/components/schemas/ApiResponse'
     */
    router.post('/verification/email/request', authenticate(), verificationController.requestEmail.bind(verificationController));

    /**
     * @swagger
     * /api/{version}/identity/verification/email/verify:
     *   post:
     *     summary: Verify email
     *     description: Verify user's email address using the token
     *     tags: [Identity - Verification]
     *     parameters:
     *       - in: path
     *         name: version
     *         required: true
     *         schema:
     *           type: string
     *           default: v1
     *         description: API version
     *     requestBody:
     *       required: true
     *       content:
     *         application/json:
     *           schema:
     *             type: object
     *             required: [token]
     *             properties:
     *               token:
     *                 type: string
     *     responses:
     *       200:
     *         description: Email verified successfully
     *         content:
     *           application/json:
     *             schema:
     *               $ref: '#/components/schemas/ApiResponse'
     */
    router.post('/verification/email/verify', verificationController.verifyEmail.bind(verificationController));

    /**
     * @swagger
     * /api/{version}/identity/verification/phone/request:
     *   post:
     *     summary: Request phone verification
     *     description: Send an SMS verification code to the user
     *     tags: [Identity - Verification]
     *     security:
     *       - bearerAuth: []
     *     parameters:
     *       - in: path
     *         name: version
     *         required: true
     *         schema:
     *           type: string
     *           default: v1
     *         description: API version
     *     requestBody:
     *       required: true
     *       content:
     *         application/json:
     *           schema:
     *             type: object
     *             required: [phoneNumber]
     *             properties:
     *               phoneNumber:
     *                 type: string
     *     responses:
     *       200:
     *         description: Verification SMS sent
     *         content:
     *           application/json:
     *             schema:
     *               $ref: '#/components/schemas/ApiResponse'
     */
    router.post('/verification/phone/request', authenticate(), verificationController.requestPhone.bind(verificationController));

    /**
     * @swagger
     * /api/{version}/identity/verification/phone/verify:
     *   post:
     *     summary: Verify phone
     *     description: Verify user's phone number using the code
     *     tags: [Identity - Verification]
     *     parameters:
     *       - in: path
     *         name: version
     *         required: true
     *         schema:
     *           type: string
     *           default: v1
     *         description: API version
     *     requestBody:
     *       required: true
     *       content:
     *         application/json:
     *           schema:
     *             type: object
     *             required: [code, phoneNumber]
     *             properties:
     *               code:
     *                 type: string
     *               phoneNumber:
     *                 type: string
     *     responses:
     *       200:
     *         description: Phone verified successfully
     *         content:
     *           application/json:
     *             schema:
     *               $ref: '#/components/schemas/ApiResponse'
     */
    router.post('/verification/phone/verify', verificationController.verifyPhone.bind(verificationController));

    /**
     * @swagger
     * /api/{version}/identity/verification/{id}/status:
     *   get:
     *     summary: Get verification status
     *     description: Check the verification status of a user
     *     tags: [Identity - Verification]
     *     security:
     *       - bearerAuth: []
     *     parameters:
     *       - in: path
     *         name: version
     *         required: true
     *         schema:
     *           type: string
     *           default: v1
     *         description: API version
     *       - in: path
     *         name: id
     *         required: true
     *         schema:
     *           type: string
     *         description: User ID
     *     responses:
     *       200:
     *         description: Verification status
     *         content:
     *           application/json:
     *             schema:
     *               allOf:
     *                 - $ref: '#/components/schemas/ApiResponse'
     *                 - type: object
     *                   properties:
     *                     data:
     *                       type: object
     *                       properties:
     *                         emailVerified:
     *                           type: boolean
     *                         phoneVerified:
     *                           type: boolean
     */
    router.get('/verification/:id/status', authenticate(), verificationController.getStatus.bind(verificationController));

    // =============================================================================
    // EN: Organization Endpoints
    // VI: Endpoints Tổ Chức
    // =============================================================================

    /**
     * @swagger
     * /api/{version}/identity/organizations:
     *   get:
     *     summary: List organizations
     *     description: List organizations visible to the current user
     *     tags: [Identity - Organizations]
     *     security:
     *       - bearerAuth: []
     *     parameters:
     *       - in: path
     *         name: version
     *         required: true
     *         schema:
     *           type: string
     *           default: v1
     *         description: API version
     *       - in: query
     *         name: page
     *         schema:
     *           type: integer
     *       - in: query
     *         name: limit
     *         schema:
     *           type: integer
     *     responses:
     *       200:
     *         description: Organizations list
     *         content:
     *           application/json:
     *             schema:
     *               allOf:
     *                 - $ref: '#/components/schemas/ApiResponse'
     *                 - type: object
     *                   properties:
     *                     data:
     *                       type: array
     *                       items:
     *                         $ref: '#/components/schemas/Organization'
     */
    router.get('/organizations', authenticate(), requirePermission('identity', 'read'), organizationController.list.bind(organizationController));

    /**
     * @swagger
     * /api/{version}/identity/organizations:
     *   post:
     *     summary: Create organization
     *     description: Create a new organization
     *     tags: [Identity - Organizations]
     *     security:
     *       - bearerAuth: []
     *     parameters:
     *       - in: path
     *         name: version
     *         required: true
     *         schema:
     *           type: string
     *           default: v1
     *         description: API version
     *     requestBody:
     *       required: true
     *       content:
     *         application/json:
     *           schema:
     *             $ref: '#/components/schemas/CreateOrganizationRequest'
     *     responses:
     *       201:
     *         description: Organization created
     *         content:
     *           application/json:
     *             schema:
     *               allOf:
     *                 - $ref: '#/components/schemas/ApiResponse'
     *                 - type: object
     *                   properties:
     *                     data:
     *                       $ref: '#/components/schemas/Organization'
     */
    router.post('/organizations', authenticate(), requirePermission('identity', 'create'), organizationController.create.bind(organizationController));

    /**
     * @swagger
     * /api/{version}/identity/organizations/{id}:
     *   get:
     *     summary: Get organization
     *     description: Get organization details
     *     tags: [Identity - Organizations]
     *     security:
     *       - bearerAuth: []
     *     parameters:
     *       - in: path
     *         name: version
     *         required: true
     *         schema:
     *           type: string
     *           default: v1
     *         description: API version
     *       - in: path
     *         name: id
     *         required: true
     *         schema:
     *           type: string
     *         description: Organization ID
     *     responses:
     *       200:
     *         description: Organization details
     *         content:
     *           application/json:
     *             schema:
     *               allOf:
     *                 - $ref: '#/components/schemas/ApiResponse'
     *                 - type: object
     *                   properties:
     *                     data:
     *                       $ref: '#/components/schemas/Organization'
     */
    router.get('/organizations/:id', authenticate(), requirePermission('identity', 'read'), organizationController.get.bind(organizationController));

    /**
     * @swagger
     * /api/{version}/identity/organizations/{id}:
     *   put:
     *     summary: Update organization
     *     description: Update organization details
     *     tags: [Identity - Organizations]
     *     security:
     *       - bearerAuth: []
     *     parameters:
     *       - in: path
     *         name: version
     *         required: true
     *         schema:
     *           type: string
     *           default: v1
     *         description: API version
     *       - in: path
     *         name: id
     *         required: true
     *         schema:
     *           type: string
     *         description: Organization ID
     *     requestBody:
     *       required: true
     *       content:
     *         application/json:
     *           schema:
     *             $ref: '#/components/schemas/UpdateOrganizationRequest'
     *     responses:
     *       200:
     *         description: Organization updated
     *         content:
     *           application/json:
     *             schema:
     *               allOf:
     *                 - $ref: '#/components/schemas/ApiResponse'
     *                 - type: object
     *                   properties:
     *                     data:
     *                       $ref: '#/components/schemas/Organization'
     */
    router.put('/organizations/:id', authenticate(), requirePermission('identity', 'update'), organizationController.update.bind(organizationController));

    /**
     * @swagger
     * /api/{version}/identity/organizations/{id}:
     *   delete:
     *     summary: Delete organization
     *     description: Delete an organization
     *     tags: [Identity - Organizations]
     *     security:
     *       - bearerAuth: []
     *     parameters:
     *       - in: path
     *         name: version
     *         required: true
     *         schema:
     *           type: string
     *           default: v1
     *         description: API version
     *       - in: path
     *         name: id
     *         required: true
     *         schema:
     *           type: string
     *         description: Organization ID
     *     responses:
     *       200:
     *         description: Organization deleted
     *         content:
     *           application/json:
     *             schema:
     *               $ref: '#/components/schemas/ApiResponse'
     */
    router.delete('/organizations/:id', authenticate(), requirePermission('identity', 'delete'), organizationController.delete.bind(organizationController));

    /**
     * @swagger
     * /api/{version}/identity/organizations/{id}/users:
     *   get:
     *     summary: Get organization users
     *     description: List users in an organization
     *     tags: [Identity - Organizations]
     *     security:
     *       - bearerAuth: []
     *     parameters:
     *       - in: path
     *         name: version
     *         required: true
     *         schema:
     *           type: string
     *           default: v1
     *         description: API version
     *       - in: path
     *         name: id
     *         required: true
     *         schema:
     *           type: string
     *         description: Organization ID
     *     responses:
     *       200:
     *         description: Users list
     *         content:
     *           application/json:
     *             schema:
     *               allOf:
     *                 - $ref: '#/components/schemas/ApiResponse'
     *                 - type: object
     *                   properties:
     *                     data:
     *                       type: array
     *                       items:
     *                         $ref: '#/components/schemas/User'
     */
    router.get('/organizations/:id/users', authenticate(), requirePermission('identity', 'read'), organizationController.getUsers.bind(organizationController));

    // =============================================================================
    // EN: Group Endpoints
    // VI: Endpoints Nhóm
    // =============================================================================

    /**
     * @swagger
     * /api/{version}/identity/organizations/{id}/groups:
     *   get:
     *     summary: List groups
     *     description: List groups in an organization
     *     tags: [Identity - Groups]
     *     security:
     *       - bearerAuth: []
     *     parameters:
     *       - in: path
     *         name: version
     *         required: true
     *         schema:
     *           type: string
     *           default: v1
     *         description: API version
     *       - in: path
     *         name: id
     *         required: true
     *         schema:
     *           type: string
     *         description: Organization ID
     *     responses:
     *       200:
     *         description: Groups list
     *         content:
     *           application/json:
     *             schema:
     *               allOf:
     *                 - $ref: '#/components/schemas/ApiResponse'
     *                 - type: object
     *                   properties:
     *                     data:
     *                       type: array
     *                       items:
     *                         $ref: '#/components/schemas/Group'
     */
    router.get('/organizations/:id/groups', authenticate(), requirePermission('identity', 'read'), groupController.list.bind(groupController));

    /**
     * @swagger
     * /api/{version}/identity/organizations/{id}/groups:
     *   post:
     *     summary: Create group
     *     description: Create a new group in an organization
     *     tags: [Identity - Groups]
     *     security:
     *       - bearerAuth: []
     *     parameters:
     *       - in: path
     *         name: version
     *         required: true
     *         schema:
     *           type: string
     *           default: v1
     *         description: API version
     *       - in: path
     *         name: id
     *         required: true
     *         schema:
     *           type: string
     *         description: Organization ID
     *     requestBody:
     *       required: true
     *       content:
     *         application/json:
     *           schema:
     *             $ref: '#/components/schemas/CreateGroupRequest'
     *     responses:
     *       201:
     *         description: Group created
     *         content:
     *           application/json:
     *             schema:
     *               allOf:
     *                 - $ref: '#/components/schemas/ApiResponse'
     *                 - type: object
     *                   properties:
     *                     data:
     *                       $ref: '#/components/schemas/Group'
     */
    router.post('/organizations/:id/groups', authenticate(), requirePermission('identity', 'create'), groupController.create.bind(groupController));

    /**
     * @swagger
     * /api/{version}/identity/groups/{id}:
     *   get:
     *     summary: Get group
     *     description: Get group details
     *     tags: [Identity - Groups]
     *     security:
     *       - bearerAuth: []
     *     parameters:
     *       - in: path
     *         name: version
     *         required: true
     *         schema:
     *           type: string
     *           default: v1
     *         description: API version
     *       - in: path
     *         name: id
     *         required: true
     *         schema:
     *           type: string
     *         description: Group ID
     *     responses:
     *       200:
     *         description: Group details
     *         content:
     *           application/json:
     *             schema:
     *               allOf:
     *                 - $ref: '#/components/schemas/ApiResponse'
     *                 - type: object
     *                   properties:
     *                     data:
     *                       $ref: '#/components/schemas/Group'
     */
    router.get('/groups/:id', authenticate(), requirePermission('identity', 'read'), groupController.get.bind(groupController));

    /**
     * @swagger
     * /api/{version}/identity/groups/{id}:
     *   put:
     *     summary: Update group
     *     description: Update group details
     *     tags: [Identity - Groups]
     *     security:
     *       - bearerAuth: []
     *     parameters:
     *       - in: path
     *         name: version
     *         required: true
     *         schema:
     *           type: string
     *           default: v1
     *         description: API version
     *       - in: path
     *         name: id
     *         required: true
     *         schema:
     *           type: string
     *         description: Group ID
     *     requestBody:
     *       required: true
     *       content:
     *         application/json:
     *           schema:
     *             $ref: '#/components/schemas/UpdateGroupRequest'
     *     responses:
     *       200:
     *         description: Group updated
     *         content:
     *           application/json:
     *             schema:
     *               allOf:
     *                 - $ref: '#/components/schemas/ApiResponse'
     *                 - type: object
     *                   properties:
     *                     data:
     *                       $ref: '#/components/schemas/Group'
     */
    router.put('/groups/:id', authenticate(), requirePermission('identity', 'update'), groupController.update.bind(groupController));

    /**
     * @swagger
     * /api/{version}/identity/groups/{id}:
     *   delete:
     *     summary: Delete group
     *     description: Delete a group
     *     tags: [Identity - Groups]
     *     security:
     *       - bearerAuth: []
     *     parameters:
     *       - in: path
     *         name: version
     *         required: true
     *         schema:
     *           type: string
     *           default: v1
     *         description: API version
     *       - in: path
     *         name: id
     *         required: true
     *         schema:
     *           type: string
     *         description: Group ID
     *     responses:
     *       200:
     *         description: Group deleted
     *         content:
     *           application/json:
     *             schema:
     *               $ref: '#/components/schemas/ApiResponse'
     */
    router.delete('/groups/:id', authenticate(), requirePermission('identity', 'delete'), groupController.delete.bind(groupController));

    /**
     * @swagger
     * /api/{version}/identity/groups/{id}/members:
     *   get:
     *     summary: Get group members
     *     description: List members of a group
     *     tags: [Identity - Groups]
     *     security:
     *       - bearerAuth: []
     *     parameters:
     *       - in: path
     *         name: version
     *         required: true
     *         schema:
     *           type: string
     *           default: v1
     *         description: API version
     *       - in: path
     *         name: id
     *         required: true
     *         schema:
     *           type: string
     *         description: Group ID
     *     responses:
     *       200:
     *         description: Members list
     *         content:
     *           application/json:
     *             schema:
     *               allOf:
     *                 - $ref: '#/components/schemas/ApiResponse'
     *                 - type: object
     *                   properties:
     *                     data:
     *                       type: array
     *                       items:
     *                         $ref: '#/components/schemas/User'
     */
    router.get('/groups/:id/members', authenticate(), requirePermission('identity', 'read'), groupController.getMembers.bind(groupController));

    /**
     * @swagger
     * /api/{version}/identity/groups/{id}/members:
     *   post:
     *     summary: Add member to group
     *     description: Add a user to a group
     *     tags: [Identity - Groups]
     *     security:
     *       - bearerAuth: []
     *     parameters:
     *       - in: path
     *         name: version
     *         required: true
     *         schema:
     *           type: string
     *           default: v1
     *         description: API version
     *       - in: path
     *         name: id
     *         required: true
     *         schema:
     *           type: string
     *         description: Group ID
     *     requestBody:
     *       required: true
     *       content:
     *         application/json:
     *           schema:
     *             type: object
     *             required: [userId]
     *             properties:
     *               userId:
     *                 type: string
     *     responses:
     *       200:
     *         description: Member added
     *         content:
     *           application/json:
     *             schema:
     *               $ref: '#/components/schemas/ApiResponse'
     */
    router.post('/groups/:id/members', authenticate(), requirePermission('identity', 'update'), groupController.addMember.bind(groupController));

    /**
     * @swagger
     * /api/{version}/identity/groups/{id}/members/{userId}:
     *   delete:
     *     summary: Remove member from group
     *     description: Remove a user from a group
     *     tags: [Identity - Groups]
     *     security:
     *       - bearerAuth: []
     *     parameters:
     *       - in: path
     *         name: version
     *         required: true
     *         schema:
     *           type: string
     *           default: v1
     *         description: API version
     *       - in: path
     *         name: id
     *         required: true
     *         schema:
     *           type: string
     *         description: Group ID
     *       - in: path
     *         name: userId
     *         required: true
     *         schema:
     *           type: string
     *         description: User ID to remove
     *     responses:
     *       200:
     *         description: Member removed
     *         content:
     *           application/json:
     *             schema:
     *               $ref: '#/components/schemas/ApiResponse'
     */
    router.delete('/groups/:id/members/:userId', authenticate(), requirePermission('identity', 'update'), groupController.removeMember.bind(groupController));

    // =============================================================================
    // EN: Alias Routes (for backward compatibility)
    // VI: Routes Alias (để tương thích ngược)
    // =============================================================================

    /**
     * @swagger
     * /api/{version}/identity/users:
     *   post:
     *     summary: Create user (stub)
     *     description: Create a new user - not yet implemented
     *     tags: [Identity - Users]
     *     security:
     *       - bearerAuth: []
     */
    router.post('/users', authenticate(), requirePermission('identity', 'create'), (req, res) => {
        res.status(501).json({
            success: false,
            error: {
                code: 'NOT_IMPLEMENTED',
                message: 'Create user endpoint is not yet implemented / Endpoint tạo người dùng chưa được triển khai'
            },
            timestamp: new Date().toISOString()
        });
    });

    /**
     * @swagger
     * /api/{version}/identity/profile:
     *   get:
     *     summary: Get current user profile
     *     description: Get profile of currently authenticated user
     *     tags: [Identity - Profile]
     *     security:
     *       - bearerAuth: []
     */
    router.get('/profile', authenticate(), (req, res) => {
        const userId = (req as any).user?.id || (req as any).user?.sub;
        if (!userId) {
            return res.status(401).json({
                success: false,
                error: { code: 'UNAUTHORIZED', message: 'Authentication required' }
            });
        }
        // Redirect to /users/:id/profile
        return res.redirect(`/api/v1/identity/users/${userId}/profile`);
    });

    return router;
};
