using Serilog;
using Serilog.Core;
using Serilog.Events;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Scripting;

namespace ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests;

/// <summary>
///     Exercises the factory that creates per-script Serilog loggers with the
///     <c>ScriptName</c> structured property pre-bound. The property is what lets
///     Admin UI filter the scripts-*.log sink by which tag/alarm emitted each event.
/// </summary>
[Trait("Category", "Unit")]
public sealed class ScriptLoggerFactoryTests
{
    /// <summary>Capturing sink that collects every emitted LogEvent for assertion.</summary>
    private sealed class CapturingSink : ILogEventSink
    {
        /// <summary>Gets the list of captured log events.</summary>
        public List<LogEvent> Events { get; } = [];

        /// <summary>Adds a log event to the captured list.</summary>
        /// <param name="logEvent">The log event to capture.</param>
        public void Emit(LogEvent logEvent) => Events.Add(logEvent);
    }

    /// <summary>Verifies that Create sets the ScriptName structured property.</summary>
    [Fact]
    public void Create_sets_ScriptName_structured_property()
    {
        var sink = new CapturingSink();
        var root = new LoggerConfiguration().MinimumLevel.Verbose().WriteTo.Sink(sink).CreateLogger();
        var factory = new ScriptLoggerFactory(root);

        var logger = factory.Create("LineRate");
        logger.Information("hello");

        sink.Events.Count.ShouldBe(1);
        var ev = sink.Events[0];
        ev.Properties.ShouldContainKey(ScriptLoggerFactory.ScriptNameProperty);
        ((ScalarValue)ev.Properties[ScriptLoggerFactory.ScriptNameProperty]).Value.ShouldBe("LineRate");
    }

    /// <summary>Verifies that each script gets its own property value.</summary>
    [Fact]
    public void Each_script_gets_its_own_property_value()
    {
        var sink = new CapturingSink();
        var root = new LoggerConfiguration().MinimumLevel.Verbose().WriteTo.Sink(sink).CreateLogger();
        var factory = new ScriptLoggerFactory(root);

        factory.Create("Alarm_A").Information("event A");
        factory.Create("Tag_B").Warning("event B");
        factory.Create("Alarm_A").Error("event A again");

        sink.Events.Count.ShouldBe(3);
        ((ScalarValue)sink.Events[0].Properties[ScriptLoggerFactory.ScriptNameProperty]).Value.ShouldBe("Alarm_A");
        ((ScalarValue)sink.Events[1].Properties[ScriptLoggerFactory.ScriptNameProperty]).Value.ShouldBe("Tag_B");
        ((ScalarValue)sink.Events[2].Properties[ScriptLoggerFactory.ScriptNameProperty]).Value.ShouldBe("Alarm_A");
    }

    /// <summary>Verifies that error-level events preserve level and exception.</summary>
    [Fact]
    public void Error_level_event_preserves_level_and_exception()
    {
        var sink = new CapturingSink();
        var root = new LoggerConfiguration().MinimumLevel.Verbose().WriteTo.Sink(sink).CreateLogger();
        var factory = new ScriptLoggerFactory(root);

        factory.Create("Test").Error(new InvalidOperationException("boom"), "script failed");

        sink.Events[0].Level.ShouldBe(LogEventLevel.Error);
        sink.Events[0].Exception.ShouldBeOfType<InvalidOperationException>();
    }

    /// <summary>Verifies that null root logger is rejected.</summary>
    [Fact]
    public void Null_root_rejected()
    {
        Should.Throw<ArgumentNullException>(() => new ScriptLoggerFactory(null!));
    }

    /// <summary>Verifies that empty script names are rejected.</summary>
    [Fact]
    public void Empty_script_name_rejected()
    {
        var root = new LoggerConfiguration().CreateLogger();
        var factory = new ScriptLoggerFactory(root);
        Should.Throw<ArgumentException>(() => factory.Create(""));
        Should.Throw<ArgumentException>(() => factory.Create("   "));
        Should.Throw<ArgumentException>(() => factory.Create(null!));
    }

    /// <summary>Verifies that the ScriptNameProperty constant is stable.</summary>
    [Fact]
    public void ScriptNameProperty_constant_is_stable()
    {
        // Stability is an external contract — the Admin UI's log filter references
        // this exact string. If it changes, the filter breaks silently.
        ScriptLoggerFactory.ScriptNameProperty.ShouldBe("ScriptName");
    }

    /// <summary>
    ///     A logger from the identity overload, when written through a
    ///     <see cref="ScriptLogTopicSink"/>, produces an entry carrying every bound id.
    /// </summary>
    [Fact]
    public void Create_identity_overload_binds_ids_onto_published_entry()
    {
        var publisher = new FakePublisher();
        var root = new LoggerConfiguration()
            .MinimumLevel.Verbose()
            .WriteTo.Sink(new ScriptLogTopicSink(publisher, LogEventLevel.Information))
            .CreateLogger();
        var factory = new ScriptLoggerFactory(root);

        var logger = factory.Create(
            scriptId: "S9", virtualTagId: "V9", alarmId: "A9", equipmentId: "EQ9");
        logger.Information("typed identity");

        publisher.Published.Count.ShouldBe(1);
        var entry = publisher.Published[0];
        entry.ScriptId.ShouldBe("S9");
        entry.VirtualTagId.ShouldBe("V9");
        entry.AlarmId.ShouldBe("A9");
        entry.EquipmentId.ShouldBe("EQ9");
        entry.Message.ShouldBe("typed identity");
    }

    /// <summary>
    ///     The identity overload leaves optional ids unbound (null on the entry) when not
    ///     supplied, binding only <c>ScriptId</c>.
    /// </summary>
    [Fact]
    public void Create_identity_overload_leaves_optional_ids_null_when_absent()
    {
        var publisher = new FakePublisher();
        var root = new LoggerConfiguration()
            .MinimumLevel.Verbose()
            .WriteTo.Sink(new ScriptLogTopicSink(publisher, LogEventLevel.Information))
            .CreateLogger();
        var factory = new ScriptLoggerFactory(root);

        factory.Create(scriptId: "S10").Information("only script id");

        var entry = publisher.Published[0];
        entry.ScriptId.ShouldBe("S10");
        entry.VirtualTagId.ShouldBeNull();
        entry.AlarmId.ShouldBeNull();
        entry.EquipmentId.ShouldBeNull();
    }

    /// <summary>Capturing publisher for the identity-overload sink tests.</summary>
    private sealed class FakePublisher : IScriptLogPublisher
    {
        /// <summary>Gets the entries published so far.</summary>
        public List<Commons.Messages.Logging.ScriptLogEntry> Published { get; } = [];

        /// <inheritdoc/>
        public void Publish(Commons.Messages.Logging.ScriptLogEntry entry) => Published.Add(entry);
    }
}
