using System.Text.Json;
using System.Text.Json.Serialization;
using AyCode.Core.Serializers;
using AyCode.Core.Serializers.Binaries;
using AyCode.Core.Tests.TestModels;

namespace AyCode.Core.Tests.Serialization;

[TestClass]
public class AcBinarySerializerSGenRuntimeCompatibilityTests
{
    private static readonly JsonSerializerOptions StjOptions = new()
    {
        ReferenceHandler = ReferenceHandler.IgnoreCycles
    };

    [TestMethod]
    public void SerializeWithSGen_DeserializeWithRuntime_LargeAndDeepData_MultipleOptions_RoundTrip()
    {
        foreach (var dataSet in GetTargetDataSets())
        {
            foreach (var optionFactory in GetOptionFactories())
            {
                var serializeOptions = optionFactory();
                serializeOptions.UseGeneratedCode = true;

                var deserializeOptions = optionFactory();
                deserializeOptions.UseGeneratedCode = false;

                var expectedJson = JsonSerializer.Serialize(dataSet.Order, StjOptions);

                var bytes = AcBinarySerializer.Serialize(dataSet.Order, serializeOptions);
                var roundTrip = AcBinaryDeserializer.Deserialize<TestOrder>(bytes, deserializeOptions);
                var actualJson = JsonSerializer.Serialize(roundTrip, StjOptions);

                Assert.AreEqual(expectedJson, actualJson, $"STJ mismatch. Dataset={dataSet.Name}, WireMode={serializeOptions.WireMode}, BaseOptions={serializeOptions.ReferenceHandling}/{serializeOptions.UseStringInterning}");

                AssertOrderEquivalent(dataSet.Order, roundTrip, $"Dataset={dataSet.Name}, WireMode={serializeOptions.WireMode}, BaseOptions={serializeOptions.ReferenceHandling}/{serializeOptions.UseStringInterning}");
            }
        }
    }

    [TestMethod]
    public void SerializeWithRuntime_DeserializeWithSGen_LargeAndDeepData_MultipleOptions_RoundTrip()
    {
        foreach (var dataSet in GetTargetDataSets())
        {
            foreach (var optionFactory in GetOptionFactories())
            {
                var serializeOptions = optionFactory();
                serializeOptions.UseGeneratedCode = false;

                var deserializeOptions = optionFactory();
                deserializeOptions.UseGeneratedCode = true;

                var expectedJson = JsonSerializer.Serialize(dataSet.Order, StjOptions);

                var bytes = AcBinarySerializer.Serialize(dataSet.Order, serializeOptions);
                var roundTrip = AcBinaryDeserializer.Deserialize<TestOrder>(bytes, deserializeOptions);
                var actualJson = JsonSerializer.Serialize(roundTrip, StjOptions);

                Assert.AreEqual(expectedJson, actualJson, $"STJ mismatch. Dataset={dataSet.Name}, WireMode={serializeOptions.WireMode}, BaseOptions={serializeOptions.ReferenceHandling}/{serializeOptions.UseStringInterning}");

                AssertOrderEquivalent(dataSet.Order, roundTrip, $"Dataset={dataSet.Name}, WireMode={serializeOptions.WireMode}, BaseOptions={serializeOptions.ReferenceHandling}/{serializeOptions.UseStringInterning}");
            }
        }
    }

    private static IEnumerable<TestDataSet> GetTargetDataSets()
    {
        return BenchmarkTestDataProvider
            .CreateTestDataSets()
            .Where(x => x.Name.StartsWith("Large") || x.Name.StartsWith("Deep"));
    }

    private static IEnumerable<Func<AcBinarySerializerOptions>> GetOptionFactories()
    {
        yield return static () =>
        {
            var options = AcBinarySerializerOptions.FastMode;
            options.WireMode = WireMode.Compact;
            return options;
        };

        yield return static () =>
        {
            var options = AcBinarySerializerOptions.FastMode;
            options.WireMode = WireMode.Fast;
            return options;
        };

        yield return static () =>
        {
            var options = AcBinarySerializerOptions.Default;
            options.WireMode = WireMode.Compact;
            return options;
        };
    }

    private static void AssertOrderEquivalent(TestOrder expected, TestOrder? actual, string context)
    {
        Assert.IsNotNull(actual, context);
        Assert.AreEqual(expected.Id, actual.Id, context);
        Assert.AreEqual(expected.OrderNumber, actual.OrderNumber, context);
        Assert.AreEqual(expected.Status, actual.Status, context);
        Assert.AreEqual(expected.Items.Count, actual.Items.Count, context);

        for (var itemIndex = 0; itemIndex < expected.Items.Count; itemIndex++)
        {
            var expectedItem = expected.Items[itemIndex];
            var actualItem = actual.Items[itemIndex];

            Assert.AreEqual(expectedItem.Id, actualItem.Id, context);
            Assert.AreEqual(expectedItem.ProductName, actualItem.ProductName, context);
            Assert.AreEqual(expectedItem.Status, actualItem.Status, context);
            Assert.AreEqual(expectedItem.Pallets.Count, actualItem.Pallets.Count, context);

            for (var palletIndex = 0; palletIndex < expectedItem.Pallets.Count; palletIndex++)
            {
                var expectedPallet = expectedItem.Pallets[palletIndex];
                var actualPallet = actualItem.Pallets[palletIndex];

                Assert.AreEqual(expectedPallet.Id, actualPallet.Id, context);
                Assert.AreEqual(expectedPallet.PalletCode, actualPallet.PalletCode, context);
                Assert.AreEqual(expectedPallet.Measurements.Count, actualPallet.Measurements.Count, context);

                for (var measurementIndex = 0; measurementIndex < expectedPallet.Measurements.Count; measurementIndex++)
                {
                    var expectedMeasurement = expectedPallet.Measurements[measurementIndex];
                    var actualMeasurement = actualPallet.Measurements[measurementIndex];

                    Assert.AreEqual(expectedMeasurement.Id, actualMeasurement.Id, context);
                    Assert.AreEqual(expectedMeasurement.Name, actualMeasurement.Name, context);
                    Assert.AreEqual(expectedMeasurement.Points.Count, actualMeasurement.Points.Count, context);

                    for (var pointIndex = 0; pointIndex < expectedMeasurement.Points.Count; pointIndex++)
                    {
                        var expectedPoint = expectedMeasurement.Points[pointIndex];
                        var actualPoint = actualMeasurement.Points[pointIndex];

                        Assert.AreEqual(expectedPoint.Id, actualPoint.Id, context);
                        Assert.AreEqual(expectedPoint.Label, actualPoint.Label, context);
                    }
                }
            }
        }
    }
}
