using AyCode.Core.Extensions;
using AyCode.Core.Serializers;
using AyCode.Core.Tests.TestModels;

namespace AyCode.Core.Tests.Serialization;

[TestClass]
public class ChainReferenceDebugTest
{
    [TestMethod]
    public void DebugChainReferences_DirectTest()
    {
        // Test ChainReferenceTracker directly
        var tracker = new AcSerializerCommon.ChainReferenceTracker();

        var category = new SharedCategory_All_True { Id = 100, Name = "TestCategory" };

        // Register using reflection (like ThenPopulate does)
        tracker.TryRegisterIIdObject(category);

        // Try to retrieve using boxed int (like MergeIIdCollection does)
        object id = 100; // Boxed int
        var found = tracker.TryGetObject(id, out var retrievedCategory);

        Console.WriteLine($"Found: {found}");
        Console.WriteLine($"Same reference: {ReferenceEquals(category, retrievedCategory)}");

        Assert.IsTrue(found, "Should find the category by ID");
        Assert.AreSame(category, retrievedCategory, "Should be same object reference");
    }

    [TestMethod]
    public void DebugSimpleChainPopulate()
    {
        var list1 = new List<SharedCategory_All_True>();
        var list2 = new List<SharedCategory_All_True>();

        var serverData = new List<SharedCategory_All_True>
        {
            new() { Id = 1, Name = "Cat1", SortOrder = 10 }
        };

        var binary = serverData.ToBinary();

        using var chain = binary.BinaryToChain<List<SharedCategory_All_True>>();

        // First populate
        chain.ThenPopulate(list1);

        // Second populate
        chain.ThenPopulate(list2);

        // Both list1[0] and list2[0] should be the same object reference
        Assert.AreSame(list1[0], list2[0], "Should be same object reference!");
    }
}
