using System.Reflection;
using System.Text.Json;
using System.Text.Json.Serialization;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.AdminUI.Components.Shared.Drivers.Forms;

namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests;

/// <summary>
///     Regression guard for the systemic driver-config enum-serialization bug found 2026-06-19.
///     Every driver-config editor serialised enum config fields (e.g. S7 <c>CpuType</c>, Modbus
///     <c>Family</c>, AbCip <c>PlcFamily</c>) as JSON <em>numbers</em> when its private static
///     <c>_jsonOpts</c> had no <see cref="JsonStringEnumConverter"/>. The driver factories, however,
///     deserialise into string-typed DTOs (+ lenient <c>ParseEnum</c>) and <em>throw</em> when binding a
///     JSON number to a <c>string?</c> — so an AdminUI-authored config that contained any enum field
///     produced a blob the driver could not parse, faulting the driver on deploy. The fix makes every
///     editor serialise enums as strings (matching the factory + the long-correct OpcUaClient template).
///     <para>v3 Batch-2 (WP3): the config serializer moved from the routed <c>*DriverPage</c> into the
///     embeddable <c>*DriverForm</c> body (shared by the page + the raw-tree DriverConfigModal), so this
///     guard now reflects over the <c>*DriverForm</c> fleet. It fails if any driver form loses its
///     string-enum converter again.</para>
/// </summary>
public sealed class DriverPageJsonConverterTests
{
    /// <summary>Every concrete <c>*DriverForm</c> in the AdminUI assembly that declares a
    /// <c>_jsonOpts</c> config serializer.</summary>
    private static IReadOnlyList<Type> DriverFormTypes { get; } =
        typeof(ModbusDriverForm).Assembly.GetTypes()
            .Where(t => t.Name.EndsWith("DriverForm", StringComparison.Ordinal) && !t.IsAbstract)
            .Where(t => t.GetField("_jsonOpts", BindingFlags.NonPublic | BindingFlags.Static) is not null)
            .OrderBy(t => t.Name)
            .ToList();

    /// <summary>xUnit theory source over the driver-form types discovered by reflection.</summary>
    public static TheoryData<Type> DriverFormsWithJsonOpts()
    {
        var data = new TheoryData<Type>();
        foreach (var t in DriverFormTypes)
            data.Add(t);
        return data;
    }

    /// <summary>Verifies every driver form's config serializer registers a string-enum converter so
    /// enum config fields round-trip as strings (and the driver factory can parse the result).</summary>
    /// <param name="formType">A driver form component type discovered by reflection.</param>
    [Theory]
    [MemberData(nameof(DriverFormsWithJsonOpts))]
    public void Driver_form_json_options_register_string_enum_converter(Type formType)
    {
        var field = formType.GetField("_jsonOpts", BindingFlags.NonPublic | BindingFlags.Static);
        var opts = (JsonSerializerOptions)field!.GetValue(null)!;
        opts.Converters.OfType<JsonStringEnumConverter>().ShouldNotBeEmpty(
            $"{formType.Name}._jsonOpts must register a JsonStringEnumConverter; otherwise AdminUI-authored " +
            "enum config fields serialise as numbers and the string-typed driver factory throws on parse.");
    }

    /// <summary>Enforces that EVERY concrete <c>*DriverForm</c> routes config serialization through a
    /// <c>_jsonOpts</c> field — otherwise a new form that serialised config a different way would slip
    /// past the converter guard above. Also a floor check so a rename can't silently shrink the set.</summary>
    [Fact]
    public void Every_driver_form_uses_a_guarded_jsonOpts_serializer()
    {
        var allDriverForms = typeof(ModbusDriverForm).Assembly.GetTypes()
            .Where(t => t.Name.EndsWith("DriverForm", StringComparison.Ordinal) && !t.IsAbstract)
            .ToList();
        allDriverForms.Count.ShouldBeGreaterThanOrEqualTo(8, "reflection should discover the full driver-form fleet");
        DriverFormTypes.Count.ShouldBe(allDriverForms.Count,
            "every *DriverForm must declare a _jsonOpts config serializer so the string-enum converter guard covers it");
    }
}
