using System.ComponentModel.DataAnnotations;
using Newtonsoft.Json;

namespace e_suite.Service.EFlowSync.Extensions;

public static class ObjectExtensions
{
    public static Dictionary<string, object?> PrimaryKeyDictionary(this Type type, object obj)
    {
        var primaryKey = new Dictionary<string, object?>();

        var properties = type.GetProperties();
        foreach (var property in properties)
        {
            var isPrimaryKey = property.CustomAttributes.SingleOrDefault(x => x.AttributeType == typeof(KeyAttribute)) != null;
            if (isPrimaryKey)
            {
                primaryKey[property.Name] = property.GetValue(obj);
            }
        }

        return primaryKey;
    }

    public static string ToPrimaryKeyJson( this Dictionary<string, object?> primaryKey )
    {
        return JsonConvert.SerializeObject(primaryKey, new JsonSerializerSettings
        {
            NullValueHandling = NullValueHandling.Ignore
        });
    }
}