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

class PermissionService {
  static async userHasPermission(userId, permissionName) {
    if (!userId || !permissionName) return false;
    try {
      const [rows] = await db.query(
        `SELECT 1 FROM user_permissions up
         JOIN permissions p ON up.permission_id = p.id
         WHERE up.user_id = ? AND p.name = ? AND p.is_active = TRUE
         LIMIT 1`,
        [userId, permissionName]
      );
      return rows.length > 0;
    } catch (error) {
      logger.error('PermissionService.userHasPermission:error', { userId, permissionName, error: error.message });
      return false;
    }
  }

  static async getAllPermissions(unitOfWork) {
    logger.info('PermissionService.getAllPermissions:start');
    try {
      const repo = new PermissionRepository(unitOfWork);
      const permissions = await repo.getAllPermissions();
      logger.info('PermissionService.getAllPermissions:success', { count: permissions.length });
      return permissions;
    } catch (error) {
      logger.error('PermissionService.getAllPermissions:error', { error: error.message });
      throw error;
    }
  }

  static async createPermission(data, userId, unitOfWork) {
    logger.info('PermissionService.createPermission:start', { userId, name: data.name });
    try {
      const repo = new PermissionRepository(unitOfWork);
      const permission = await repo.createPermission({ ...data, created_by: userId });
      logger.info('PermissionService.createPermission:success', { id: permission.id, name: permission.name });
      return permission;
    } catch (error) {
      logger.error('PermissionService.createPermission:error', { userId, error: error.message });
      throw error;
    }
  }
}

module.exports = PermissionService;