using AyCode.Core.Helpers;
using AyCode.Core.Serializers.Jsons;

namespace AyCode.Core.Serializers;

/// <summary>
/// Utility class providing common cross-type deserialization functionality.
/// Shared by both JSON and Binary deserializers.
/// </summary>
public class DeserializeCrossTypeBase : TypeMetadataBase
{
    protected DeserializeCrossTypeBase(Type type) : base(type, JsonUtilities.HasJsonIgnoreAttribute)
    {}

    /// <summary>
    /// Checks if two types are the same (fast path detection).
    /// </summary>
    public static bool IsSameType(Type sourceType, Type destType)
        => sourceType == destType;

    /// <summary>
    /// Validates that target object for populate is not null.
    /// </summary>
    public static void ValidatePopulateTarget<TDest>(TDest target) where TDest : class
    {
        if (target == null)
            throw new ArgumentNullException(nameof(target));
    }

    /// <summary>
    /// Checks if data is empty or null marker.
    /// </summary>
    public static bool IsEmptyData(ReadOnlySpan<byte> data, byte nullMarker)
    {
        if (data.Length == 0) return true;
        if (data.Length == 1 && data[0] == nullMarker) return true;
        return false;
    }

    /// <summary>
    /// Checks if JSON data is effectively empty.
    /// </summary>
    public static bool IsEmptyJsonData(ReadOnlySpan<byte> data)
    {
        if (data.Length == 0) return true;

        // Check for "null" (4 bytes)
        if (data.Length == 4)
        {
            return data[0] == (byte)'n' &&
                   data[1] == (byte)'u' &&
                   data[2] == (byte)'l' &&
                   data[3] == (byte)'l';
        }

        return false;
    }
}
