using System;
using System.Data.Common;

namespace AS400API.Infrastructure;

public static class DataReaderExtensions
{
    public static object? GetNormalizedValue(this DbDataReader reader, int ordinal)
    {
        if (reader.IsDBNull(ordinal))
        {
            return null;
        }

        var value = reader.GetValue(ordinal);

        if (value is string stringValue)
        {
            var dataTypeName = reader.GetDataTypeName(ordinal)?.Trim();
            if (!string.IsNullOrEmpty(dataTypeName)
                && dataTypeName.StartsWith("CHAR", StringComparison.OrdinalIgnoreCase)
                && !dataTypeName.Contains("VARYING", StringComparison.OrdinalIgnoreCase))
            {
                return stringValue.TrimEnd();
            }
        }

        return value;
    }
}
