using Bunit;
using Microsoft.AspNetCore.Components;
using ZB.MOM.WW.ScadaBridge.CentralUI.Components.Shared;

namespace ZB.MOM.WW.ScadaBridge.CentralUI.Tests.Shared;

/// <summary>
/// Component tests for the OnTrue/WhileTrue mode selector that
/// <see cref="ScriptTriggerEditor"/> exposes for Conditional and Expression
/// triggers.
/// </summary>
public class ScriptTriggerEditorTests : BunitContext
{
    private const string ConditionalConfig =
        @"{""attributeName"":""Temp"",""operator"":"">"",""threshold"":50}";

    private const string ConditionalWhileTrueConfig =
        @"{""attributeName"":""Temp"",""operator"":"">"",""threshold"":50,""mode"":""WhileTrue""}";

    [Fact]
    public void SelectingWhileTrue_EmitsConfigWithWhileTrueMode()
    {
        ScriptTriggerValue? captured = null;
        var cut = Render<ScriptTriggerEditor>(ps => ps
            .Add(p => p.TriggerType, "Conditional")
            .Add(p => p.TriggerConfig, ConditionalConfig)
            .Add(p => p.Changed,
                EventCallback.Factory.Create<ScriptTriggerValue>(this, v => captured = v)));

        cut.Find("#script-trigger-mode").Change("WhileTrue");

        Assert.NotNull(captured);
        Assert.Contains("\"mode\":\"WhileTrue\"", captured!.Config);
    }

    [Fact]
    public void ModeSelector_DefaultsToOnTrue_WhenConfigHasNoMode()
    {
        ScriptTriggerValue? captured = null;
        var cut = Render<ScriptTriggerEditor>(ps => ps
            .Add(p => p.TriggerType, "Conditional")
            .Add(p => p.TriggerConfig, ConditionalConfig)
            .Add(p => p.Changed,
                EventCallback.Factory.Create<ScriptTriggerValue>(this, v => captured = v)));

        // Change the threshold to force an emit without touching the mode.
        cut.Find("input[type=number]").Input("75");

        Assert.NotNull(captured);
        Assert.Contains("\"mode\":\"OnTrue\"", captured!.Config);
    }

    [Fact]
    public void LoadedWhileTrueMode_IsRetainedAcrossAnUnrelatedEdit()
    {
        ScriptTriggerValue? captured = null;
        var cut = Render<ScriptTriggerEditor>(ps => ps
            .Add(p => p.TriggerType, "Conditional")
            .Add(p => p.TriggerConfig, ConditionalWhileTrueConfig)
            .Add(p => p.Changed,
                EventCallback.Factory.Create<ScriptTriggerValue>(this, v => captured = v)));

        // Editing the threshold must not silently drop the loaded WhileTrue mode.
        cut.Find("input[type=number]").Input("75");

        Assert.NotNull(captured);
        Assert.Contains("\"mode\":\"WhileTrue\"", captured!.Config);
    }
}
