using Microsoft.AspNetCore.WebUtilities;
using System.Reflection;

namespace Leanetec.EConnect.Infrastructure;

public static class ObjectExtensions
{
    public static Dictionary<string, string?> ToPropertyDictionary(this object obj)
    {
        return obj
        .GetType()
        .GetProperties(BindingFlags.Instance | BindingFlags.Public)
        .ToDictionary(
            prop => prop.Name.ToCamelCase(),
            prop => prop.GetValue(obj).ToSafeString()
        );
    }

    public static Dictionary<string, string?> ToPropertyDictionary(this Dictionary<string, object?> obj)
    {
        return obj
        .ToDictionary(
            prop => prop.Key.ToCamelCase(),
            prop => prop.Value?.ToString()
        );
    }

    public static string? ToSafeString(this object? obj)
        => obj is bool b
            ? (b ? "true" : "false")
            : obj?.ToString();

    public static string? AddQueryString(this string? route, Dictionary<string, string?> queryParams)
    {
        if (queryParams.Count > 0)
            route = QueryHelpers.AddQueryString(route ?? string.Empty, queryParams);
        return route;
    }

    public static string? AddQueryString(this string? route, object queryParams) => route.AddQueryString(queryParams.ToPropertyDictionary());

    public static string ToCamelCase(this string input)
    {
        if (string.IsNullOrWhiteSpace(input))
            return input;

        if (char.IsLower(input[0]))
            return input;
        
        return char.ToLowerInvariant(input[0]) + input[1..];
    }
}