
using System.Linq.Expressions;
using System.Reflection;

namespace ReAct_PME.WebUI.Pages
{
    public static class EnumerableExtensions
    {
        public static IEnumerable<T> OrderByDynamic<T>(this IEnumerable<T> source, string propertyPath, bool ascending)
        {
            if (string.IsNullOrWhiteSpace(propertyPath)) return source;

            // Split les propriétés imbriquées
            var props = propertyPath.Split('.');
            Type type = typeof(T);
            ParameterExpression parameter = Expression.Parameter(type, "x");
            Expression propertyAccess = parameter;

            foreach (var prop in props)
            {
                PropertyInfo? property = type.GetProperty(prop);
                if (property == null) return source; // Propriété non trouvée
                propertyAccess = Expression.Property(propertyAccess, property);
                type = property.PropertyType;
            }

            // Converti en Func<T, object>
            var converted = Expression.Convert(propertyAccess, typeof(object));
            var lambda = Expression.Lambda<Func<T, object>>(converted, parameter);

            return ascending
                ? source.OrderBy(lambda.Compile())
                : source.OrderByDescending(lambda.Compile());
        }
    }
}
