const UnitOfWork = require('../../database/UnitOfWork');
const PermissionService = require('../../services/permissions/PermissionService');
const PermissionRepository = require('../../repositories/permissions/PermissionRepository');
const { logger } = require('../../middleware/logger');

class PermissionController {
  static async list(req, res) {
    const unitOfWork = new UnitOfWork();
    await unitOfWork.start();
    try {
      const permissions = await PermissionService.getAllPermissions(unitOfWork);
      await unitOfWork.commit();
      res.json({ success: true, permissions });
    } catch (error) {
      await unitOfWork.rollback(error);
      res.status(500).json({ success: false, message: error.message });
    }
  }

  static async create(req, res) {
    const { name, description, is_active } = req.body;
    const userId = req.user.userId; // Get user ID from access token
    if (!name) {
      return res.status(400).json({ success: false, message: 'Permission name is required' });
    }
    const unitOfWork = new UnitOfWork();
    await unitOfWork.start();
    try {
      const permission = await PermissionService.createPermission({ name, description, is_active }, userId, unitOfWork);
      await unitOfWork.commit();
      res.status(201).json({ success: true, permission });
    } catch (error) {
      await unitOfWork.rollback(error);
      res.status(400).json({ success: false, message: error.message });
    }
  }

  static async getUserPermissions(req, res) {
    // Prevent caching of permission responses
    res.set('Cache-Control', 'no-store, no-cache, must-revalidate, private');
    res.set('Pragma', 'no-cache');
    res.set('Vary', 'Authorization');

    // Access control: only self or admin/super_admin can view
    const requestedUserId = Number(req.params.id);
    const requesterUserId = Number(req.user.userId ?? req.user.id ?? req.user.sub);
    const requesterRole = req.user.role;

    if (requestedUserId !== requesterUserId && requesterRole !== 'admin' && requesterRole !== 'super_admin') {
      const requesterIdLog = Number.isNaN(requesterUserId) ? (req.user.userId ?? req.user.id ?? req.user.sub) : requesterUserId;
      logger.warn('PermissionController.getUserPermissions:forbidden', {
        requestedUserId,
        requesterUserId: requesterIdLog,
        requesterRole,
        route: req.originalUrl
      });
      return res.status(403).json({ success: false, message: 'Forbidden' });
    }

    const unitOfWork = new UnitOfWork();
    await unitOfWork.start();
    try {
      // Use PermissionRepository for data access
      const repo = new PermissionRepository(unitOfWork);
      const permissions = await repo.getPermissionsByUserId(requestedUserId);
      await unitOfWork.commit();
      res.json({ success: true, permissions });
    } catch (error) {
      await unitOfWork.rollback(error);
      res.status(500).json({ success: false, message: error.message });
    }
  }
}

module.exports = PermissionController;
module.exports = PermissionController;
