export function createPermissionHelpers({ pool }) {
  async function checkPermission(userId, permissionCode) {
    try {
      const adminResult = await pool.query(
        'SELECT is_admin FROM users WHERE id = $1',
        [userId]
      );
      if (adminResult.rows.length > 0 && adminResult.rows[0].is_admin) return true;

      const result = await pool.query(
        `SELECT COUNT(*) AS has_permission
           FROM user_permissions up
           JOIN permissions p ON up.permission_id = p.id
          WHERE up.user_id = $1 AND p.code = $2`,
        [userId, permissionCode]
      );
      return Number(result.rows[0].has_permission) > 0;
    } catch (error) {
      console.error('Error checking permission:', error);
      return false;
    }
  }

  function requirePermission(permissionCode) {
    return async (req, res, next) => {
      try {
        if (!req.user?.id) {
          return res.status(401).json({ error: 'Authentication required' });
        }
        const hasPermission = await checkPermission(req.user.id, permissionCode);
        if (!hasPermission) {
          return res.status(403).json({
            error: 'Insufficient permissions',
            requiredPermission: permissionCode,
          });
        }
        next();
      } catch (error) {
        console.error('Permission middleware error:', error);
        res.status(500).json({ error: 'Server error checking permissions' });
      }
    };
  }

  async function getUserPermissions(userId) {
    try {
      const adminResult = await pool.query(
        'SELECT is_admin FROM users WHERE id = $1',
        [userId]
      );
      if (adminResult.rows.length === 0) return [];

      if (adminResult.rows[0].is_admin) {
        const allPermissions = await pool.query('SELECT code FROM permissions');
        return allPermissions.rows.map((p) => p.code);
      }

      const permissions = await pool.query(
        `SELECT p.code
           FROM permissions p
           JOIN user_permissions up ON p.id = up.permission_id
          WHERE up.user_id = $1`,
        [userId]
      );
      return permissions.rows.map((p) => p.code);
    } catch (error) {
      console.error('Error getting user permissions:', error);
      return [];
    }
  }

  return { checkPermission, requirePermission, getUserPermissions };
}
