import { Router } from 'express';

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

import { complianceController } from './compliance';
import { policyGovernanceController } from './policy';
import { reportingController } from './reporting';
import { riskController } from './risk';

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

    // =============================================================================
    // EN: Compliance Reports Endpoints
    // VI: Endpoints Báo Cáo Tuân Thủ
    // =============================================================================

    /**
     * @swagger
     * /api/{version}/governance/compliance/reports:
     *   get:
     *     summary: List compliance reports
     *     description: List compliance reports
     *     tags: [Governance - Compliance]
     *     security:
     *       - bearerAuth: []
     *     parameters:
     *       - in: path
     *         name: version
     *         required: true
     *         schema:
     *           type: string
     *           default: v1
     *         description: API version
     *     responses:
     *       200:
     *         description: Reports list
     *         content:
     *           application/json:
     *             schema:
     *               allOf:
     *                 - $ref: '#/components/schemas/ApiResponse'
     *                 - type: object
     *                   properties:
     *                     data:
     *                       type: array
     *                       items:
     *                         $ref: '#/components/schemas/ComplianceReport'
     */
    router.get('/compliance/reports', authenticate(), requirePermission('governance', 'read'), complianceController.list.bind(complianceController));

    /**
     * @swagger
     * /api/{version}/governance/compliance/reports/generate:
     *   post:
     *     summary: Generate compliance report
     *     description: Generate a new compliance report
     *     tags: [Governance - Compliance]
     *     security:
     *       - bearerAuth: []
     *     parameters:
     *       - in: path
     *         name: version
     *         required: true
     *         schema:
     *           type: string
     *           default: v1
     *         description: API version
     *     responses:
     *       201:
     *         description: Report generation started
     *         content:
     *           application/json:
     *             schema:
     *               $ref: '#/components/schemas/ApiResponse'
     */
    router.post('/compliance/reports/generate', authenticate(), requirePermission('governance', 'create'), complianceController.generate.bind(complianceController));

    /**
     * @swagger
     * /api/{version}/governance/compliance/reports/{id}:
     *   get:
     *     summary: Get compliance report
     *     description: Get compliance report details
     *     tags: [Governance - Compliance]
     *     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: Report ID
     *     responses:
     *       200:
     *         description: Report details
     *         content:
     *           application/json:
     *             schema:
     *               allOf:
     *                 - $ref: '#/components/schemas/ApiResponse'
     *                 - type: object
     *                   properties:
     *                     data:
     *                       $ref: '#/components/schemas/ComplianceReport'
     */
    router.get('/compliance/reports/:id', authenticate(), requirePermission('governance', 'read'), complianceController.get.bind(complianceController));

    /**
     * @swagger
     * /api/{version}/governance/compliance/reports/{id}/export:
     *   get:
     *     summary: Export compliance report
     *     description: Export compliance report to file
     *     tags: [Governance - Compliance]
     *     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: Report ID
     *       - in: query
     *         name: format
     *         schema:
     *           type: string
     *           enum: [pdf, csv]
     *           default: pdf
     *     responses:
     *       200:
     *         description: Export successful
     *         content:
     *           application/json:
     *             schema:
     *               type: object // File download
     */
    router.get('/compliance/reports/:id/export', authenticate(), requirePermission('governance', 'read'), complianceController.export.bind(complianceController));

    /**
     * @swagger
     * /api/{version}/governance/compliance/reports/{id}/publish:
     *   post:
     *     summary: Publish compliance report
     *     description: Publish a compliance report
     *     tags: [Governance - Compliance]
     *     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: Report ID
     *     responses:
     *       200:
     *         description: Report published
     *         content:
     *           application/json:
     *             schema:
     *               $ref: '#/components/schemas/ApiResponse'
     */
    router.post('/compliance/reports/:id/publish', authenticate(), requirePermission('governance', 'update'), complianceController.publish.bind(complianceController));

    // =============================================================================
    // EN: Policy Governance Endpoints
    // VI: Endpoints Quản Trị Policy
    // =============================================================================

    /**
     * @swagger
     * /api/{version}/governance/policies/templates:
     *   get:
     *     summary: List policy templates
     *     description: List available policy templates
     *     tags: [Governance - Policy]
     *     security:
     *       - bearerAuth: []
     *     parameters:
     *       - in: path
     *         name: version
     *         required: true
     *         schema:
     *           type: string
     *           default: v1
     *         description: API version
     *     responses:
     *       200:
     *         description: Templates list
     *         content:
     *           application/json:
     *             schema:
     *               allOf:
     *                 - $ref: '#/components/schemas/ApiResponse'
     *                 - type: object
     *                   properties:
     *                     data:
     *                       type: array
     *                       items:
     *                         $ref: '#/components/schemas/PolicyTemplate'
     */
    router.get('/policies/templates', authenticate(), requirePermission('governance', 'read'), policyGovernanceController.getTemplates.bind(policyGovernanceController));

    /**
     * @swagger
     * /api/{version}/governance/policies/templates:
     *   post:
     *     summary: Create policy template
     *     description: Create a new policy template
     *     tags: [Governance - Policy]
     *     security:
     *       - bearerAuth: []
     *     parameters:
     *       - in: path
     *         name: version
     *         required: true
     *         schema:
     *           type: string
     *           default: v1
     *         description: API version
     *     responses:
     *       201:
     *         description: Template created
     *         content:
     *           application/json:
     *             schema:
     *               $ref: '#/components/schemas/ApiResponse'
     */
    router.post('/policies/templates', authenticate(), requirePermission('governance', 'create'), policyGovernanceController.createTemplate.bind(policyGovernanceController));

    /**
     * @swagger
     * /api/{version}/governance/policies/{id}/versions:
     *   get:
     *     summary: Get policy versions
     *     description: Get version history of a policy
     *     tags: [Governance - Policy]
     *     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: Policy ID
     *     responses:
     *       200:
     *         description: Policy versions
     *         content:
     *           application/json:
     *             schema:
     *               allOf:
     *                 - $ref: '#/components/schemas/ApiResponse'
     *                 - type: object
     *                   properties:
     *                     data:
     *                       type: array
     *                       items:
     *                         $ref: '#/components/schemas/PolicyVersion'
     */
    router.get('/policies/:id/versions', authenticate(), requirePermission('governance', 'read'), policyGovernanceController.getVersions.bind(policyGovernanceController));

    /**
     * @swagger
     * /api/{version}/governance/policies/{id}/test:
     *   post:
     *     summary: Test policy
     *     description: Test a policy against a context
     *     tags: [Governance - Policy]
     *     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: Policy ID
     *     requestBody:
     *       content:
     *         application/json:
     *           schema:
     *             type: object
     *             properties:
     *               context:
     *                 type: object
     *     responses:
     *       200:
     *         description: Test result
     *         content:
     *           application/json:
     *             schema:
     *               allOf:
     *                 - $ref: '#/components/schemas/ApiResponse'
     *                 - type: object
     *                   properties:
     *                     data:
     *                       type: object
     *                       properties:
     *                         allowed:
     *                           type: boolean
     */
    router.post('/policies/:id/test', authenticate(), requirePermission('governance', 'read'), policyGovernanceController.test.bind(policyGovernanceController));

    // =============================================================================
    // EN: Risk Management Endpoints
    // VI: Endpoints Quản Lý Rủi Ro
    // =============================================================================

    /**
     * @swagger
     * /api/{version}/governance/risk/scores:
     *   get:
     *     summary: List risk scores
     *     description: List user risk scores
     *     tags: [Governance - Risk]
     *     security:
     *       - bearerAuth: []
     *     parameters:
     *       - in: path
     *         name: version
     *         required: true
     *         schema:
     *           type: string
     *           default: v1
     *         description: API version
     *     responses:
     *       200:
     *         description: Risk scores
     *         content:
     *           application/json:
     *             schema:
     *               allOf:
     *                 - $ref: '#/components/schemas/ApiResponse'
     *                 - type: object
     *                   properties:
     *                     data:
     *                       type: array
     *                       items:
     *                         $ref: '#/components/schemas/RiskScore'
     */
    router.get('/risk/scores', authenticate(), requirePermission('governance', 'read'), riskController.list.bind(riskController));

    /**
     * @swagger
     * /api/{version}/governance/risk/scores/{userId}:
     *   get:
     *     summary: Get user risk score
     *     description: Get risk score for a specific user
     *     tags: [Governance - Risk]
     *     security:
     *       - bearerAuth: []
     *     parameters:
     *       - in: path
     *         name: version
     *         required: true
     *         schema:
     *           type: string
     *           default: v1
     *         description: API version
     *       - in: path
     *         name: userId
     *         required: true
     *         schema:
     *           type: string
     *         description: User ID
     *     responses:
     *       200:
     *         description: User risk score
     *         content:
     *           application/json:
     *             schema:
     *               allOf:
     *                 - $ref: '#/components/schemas/ApiResponse'
     *                 - type: object
     *                   properties:
     *                     data:
     *                       $ref: '#/components/schemas/RiskScore'
     */
    router.get('/risk/scores/:userId', authenticate(), requirePermission('governance', 'read'), riskController.getScore.bind(riskController));

    /**
     * @swagger
     * /api/{version}/governance/risk/calculate:
     *   post:
     *     summary: Calculate risk score
     *     description: Trigger risk score calculation
     *     tags: [Governance - Risk]
     *     security:
     *       - bearerAuth: []
     *     parameters:
     *       - in: path
     *         name: version
     *         required: true
     *         schema:
     *           type: string
     *           default: v1
     *         description: API version
     *     responses:
     *       200:
     *         description: Calculation started
     *         content:
     *           application/json:
     *             schema:
     *               $ref: '#/components/schemas/ApiResponse'
     */
    router.post('/risk/calculate', authenticate(), requirePermission('governance', 'update'), riskController.calculate.bind(riskController));

    /**
     * @swagger
     * /api/{version}/governance/risk/dashboard:
     *   get:
     *     summary: Risk dashboard
     *     description: Get risk dashboard data
     *     tags: [Governance - Risk]
     *     security:
     *       - bearerAuth: []
     *     parameters:
     *       - in: path
     *         name: version
     *         required: true
     *         schema:
     *           type: string
     *           default: v1
     *         description: API version
     *     responses:
     *       200:
     *         description: Dashboard data
     *         content:
     *           application/json:
     *             schema:
     *               $ref: '#/components/schemas/ApiResponse'
     */
    router.get('/risk/dashboard', authenticate(), requirePermission('governance', 'read'), riskController.dashboard.bind(riskController));

    // =============================================================================
    // EN: Reporting Endpoints
    // VI: Endpoints Báo Cáo
    // =============================================================================

    /**
     * @swagger
     * /api/{version}/governance/reports/access-summary:
     *   get:
     *     summary: Access summary report
     *     description: Get access summary report
     *     tags: [Governance - Reports]
     *     security:
     *       - bearerAuth: []
     *     parameters:
     *       - in: path
     *         name: version
     *         required: true
     *         schema:
     *           type: string
     *           default: v1
     *         description: API version
     *     responses:
     *       200:
     *         description: Report data
     *         content:
     *           application/json:
     *             schema:
     *               $ref: '#/components/schemas/ApiResponse'
     */
    router.get('/reports/access-summary', authenticate(), requirePermission('governance', 'read'), reportingController.accessSummary.bind(reportingController));

    /**
     * @swagger
     * /api/{version}/governance/reports/user-activity:
     *   get:
     *     summary: User activity report
     *     description: Get user activity report
     *     tags: [Governance - Reports]
     *     security:
     *       - bearerAuth: []
     *     parameters:
     *       - in: path
     *         name: version
     *         required: true
     *         schema:
     *           type: string
     *           default: v1
     *         description: API version
     *     responses:
     *       200:
     *         description: Report data
     *         content:
     *           application/json:
     *             schema:
     *               $ref: '#/components/schemas/ApiResponse'
     */
    router.get('/reports/user-activity', authenticate(), requirePermission('governance', 'read'), reportingController.userActivity.bind(reportingController));

    /**
     * @swagger
     * /api/{version}/governance/reports/security-events:
     *   get:
     *     summary: Security events report
     *     description: Get security events report
     *     tags: [Governance - Reports]
     *     security:
     *       - bearerAuth: []
     *     parameters:
     *       - in: path
     *         name: version
     *         required: true
     *         schema:
     *           type: string
     *           default: v1
     *         description: API version
     *     responses:
     *       200:
     *         description: Report data
     *         content:
     *           application/json:
     *             schema:
     *               $ref: '#/components/schemas/ApiResponse'
     */
    router.get('/reports/security-events', authenticate(), requirePermission('governance', 'read'), reportingController.securityEvents.bind(reportingController));

    /**
     * @swagger
     * /api/{version}/governance/reports/compliance-status:
     *   get:
     *     summary: Compliance status report
     *     description: Get compliance status report
     *     tags: [Governance - Reports]
     *     security:
     *       - bearerAuth: []
     *     parameters:
     *       - in: path
     *         name: version
     *         required: true
     *         schema:
     *           type: string
     *           default: v1
     *         description: API version
     *     responses:
     *       200:
     *         description: Report data
     *         content:
     *           application/json:
     *             schema:
     *               $ref: '#/components/schemas/ApiResponse'
     */
    router.get('/reports/compliance-status', authenticate(), requirePermission('governance', 'read'), reportingController.complianceStatus.bind(reportingController));

    /**
     * @swagger
     * /api/{version}/governance/reports/risk-overview:
     *   get:
     *     summary: Risk overview report
     *     description: Get risk overview report
     *     tags: [Governance - Reports]
     *     security:
     *       - bearerAuth: []
     *     parameters:
     *       - in: path
     *         name: version
     *         required: true
     *         schema:
     *           type: string
     *           default: v1
     *         description: API version
     *     responses:
     *       200:
     *         description: Report data
     *         content:
     *           application/json:
     *             schema:
     *               $ref: '#/components/schemas/ApiResponse'
     */
    router.get('/reports/risk-overview', authenticate(), requirePermission('governance', 'read'), reportingController.riskOverview.bind(reportingController));

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

    /**
     * @swagger
     * /api/{version}/governance/audit-logs:
     *   get:
     *     summary: Get audit logs (stub)
     *     description: Get audit logs - not yet implemented
     *     tags: [Governance]
     *     security:
     *       - bearerAuth: []
     */
    router.get('/audit-logs', authenticate(), requirePermission('governance', 'read'), (req, res) => {
        res.status(501).json({
            success: false,
            error: {
                code: 'NOT_IMPLEMENTED',
                message: 'Audit logs endpoint is not yet implemented / Endpoint audit logs chưa được triển khai'
            },
            timestamp: new Date().toISOString()
        });
    });

    /**
     * @swagger
     * /api/{version}/governance/compliance:
     *   get:
     *     summary: Get compliance status (alias)
     *     description: Alias for /reports/compliance-status
     *     tags: [Governance]
     *     security:
     *       - bearerAuth: []
     */
    router.get('/compliance', authenticate(), requirePermission('governance', 'read'), reportingController.complianceStatus.bind(reportingController));

    return router;
};
