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

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

/// <summary>
/// Verifies that <see cref="UnsTreeService.LoadTagDriversForEquipmentAsync"/> surfaces each
/// candidate driver's <c>DriverType</c> alongside its id and display string, so the UNS TagModal
/// can later dispatch to a per-driver-type typed tag-config editor (F-uns-1).
/// </summary>
[Trait("Category", "Unit")]
public sealed class UnsTreeServiceTagDriversTests
{
    /// <summary>
    /// A driver loaded for an equipment carries its <c>DriverType</c> in the returned tuple.
    /// </summary>
    [Fact]
    public async Task LoadTagDriversForEquipment_surfaces_driver_type()
    {
        var dbName = $"uns-tagdrivers-{Guid.NewGuid():N}";

        using (var db = UnsTreeTestDb.CreateNamed(dbName))
        {
            db.ServerClusters.Add(new ServerCluster
            {
                ClusterId = "MAIN",
                Name = "Main",
                Enterprise = "zb",
                Site = "warsaw-west",
                RedundancyMode = RedundancyMode.None,
                CreatedBy = "test",
            });
            db.UnsAreas.Add(new UnsArea { UnsAreaId = "AREA-1", ClusterId = "MAIN", Name = "a" });
            db.UnsLines.Add(new UnsLine { UnsLineId = "LINE-1", UnsAreaId = "AREA-1", Name = "l" });
            db.Equipment.Add(new Equipment
            {
                EquipmentId = "EQ-1",
                EquipmentUuid = Guid.NewGuid(),
                UnsLineId = "LINE-1",
                Name = "machine-1",
                MachineCode = "machine_001",
            });
            db.Namespaces.Add(new Namespace
            {
                NamespaceId = "NS-EQ",
                ClusterId = "MAIN",
                Kind = NamespaceKind.Equipment,
                NamespaceUri = "urn:zb:eq",
            });
            db.DriverInstances.Add(new DriverInstance
            {
                DriverInstanceId = "DRV-EQ",
                ClusterId = "MAIN",
                NamespaceId = "NS-EQ",
                Name = "equipment driver",
                DriverType = "ModbusTcp",
                DriverConfig = "{}",
            });
            db.SaveChanges();
        }

        var service = new UnsTreeService(UnsTreeTestDb.Factory(dbName));

        var drivers = await service.LoadTagDriversForEquipmentAsync("EQ-1");

        drivers.Count.ShouldBe(1);
        drivers[0].DriverInstanceId.ShouldBe("DRV-EQ");
        drivers[0].DriverType.ShouldBe("ModbusTcp");
    }
}
