using System.Reflection;
using System.Text.Json;

namespace ColaFlow.API.Tests.Helpers;

public static class TestHelpers
{
    /// <summary>
    /// Get property value from an anonymous object using reflection
    /// </summary>
    public static T? GetPropertyValue<T>(object obj, string propertyName)
    {
        var property = obj.GetType().GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance);
        if (property == null)
        {
            throw new ArgumentException($"Property '{propertyName}' not found on type '{obj.GetType().Name}'");
        }

        var value = property.GetValue(obj);
        if (value is T typedValue)
        {
            return typedValue;
        }

        if (value == null && default(T) == null)
        {
            return default;
        }

        // Try conversion
        try
        {
            return (T)Convert.ChangeType(value, typeof(T))!;
        }
        catch
        {
            throw new InvalidCastException($"Cannot convert property '{propertyName}' value '{value}' to type '{typeof(T).Name}'");
        }
    }

    /// <summary>
    /// Check if object has a property with a specific value
    /// </summary>
    public static bool HasPropertyWithValue<T>(object obj, string propertyName, T expectedValue)
    {
        try
        {
            var actualValue = GetPropertyValue<T>(obj, propertyName);
            return EqualityComparer<T>.Default.Equals(actualValue, expectedValue);
        }
        catch
        {
            return false;
        }
    }
}
