using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;

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

/// <summary>
/// Verifies the live-edit compose seam (<see cref="AddressSpaceComposer.Compose"/>) carries the
/// <see cref="VirtualTag.Historize"/> entity column onto the resulting
/// <see cref="EquipmentVirtualTagPlan.Historize"/> (H5a). The flag was authored in the UI but
/// never threaded onto the plan, leaving equipment-namespace runtime historization dead. Both a
/// true and a false case are asserted so the default (false) and the explicit set both prove out.
/// </summary>
public sealed class AddressSpaceComposerVirtualTagHistorizeTests
{
    [Fact]
    public void Compose_carries_virtual_tag_historize_flag_onto_plan()
    {
        // v3: no Namespace entity; DriverInstance no longer binds a Namespace; Equipment no longer
        // binds a driver. The dependency tag is not seeded here — the composer no longer takes tags
        // (they're dark until Batch 4) and the VirtualTag subject of this test is a LIVE surface.
        var driver = new DriverInstance
        {
            DriverInstanceId = "drv-1",
            ClusterId = "c1",
            Name = "Modbus1",
            DriverType = "Modbus",
            DriverConfig = "{}",
        };
        var area = new UnsArea { UnsAreaId = "area-1", ClusterId = "c1", Name = "filling" };
        var line = new UnsLine { UnsLineId = "line-1", UnsAreaId = "area-1", Name = "line-1" };
        var equip = new Equipment { EquipmentId = "eq-1", UnsLineId = "line-1", Name = "TestMachine_001", MachineCode = "TESTMACHINE_001" };
        var script = new Script
        {
            ScriptId = "s-1",
            Name = "passthru",
            SourceCode = "return ctx.GetTag(\"TestMachine_001.Source\").Value;",
            SourceHash = "hash-1",
        };
        // Two VirtualTags off the same script: one historized, one not.
        var vtHist = new VirtualTag { VirtualTagId = "vt-hist", EquipmentId = "eq-1", Name = "Historized", DataType = "Int32", ScriptId = "s-1", Historize = true };
        var vtPlain = new VirtualTag { VirtualTagId = "vt-plain", EquipmentId = "eq-1", Name = "Plain", DataType = "Int32", ScriptId = "s-1", Historize = false };

        var result = AddressSpaceComposer.Compose(
            new[] { area }, new[] { line }, new[] { equip },
            new[] { driver }, Array.Empty<ScriptedAlarm>(),
            virtualTags: new[] { vtHist, vtPlain },
            scripts: new[] { script });

        result.EquipmentVirtualTags.Single(p => p.VirtualTagId == "vt-hist").Historize.ShouldBeTrue();
        result.EquipmentVirtualTags.Single(p => p.VirtualTagId == "vt-plain").Historize.ShouldBeFalse();
    }
}
