using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.AdminUI.ScriptAnalysis;

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

public sealed class FormatTests
{
    private static readonly ScriptAnalysisService Svc = new();
    private static string Fmt(string code) => Svc.Format(new FormatRequest(code)).Code;

    [Fact] public void Reflows_crammed_source_to_canonical_layout()
    {
        var outp = Fmt("var x=1;return x;");
        outp.ShouldNotBe("var x=1;return x;");      // it changed
        outp.ShouldContain("\n");                    // statements split onto separate lines
        outp.ShouldContain("var x = 1;");            // canonical spacing
    }

    [Fact] public void Empty_code_is_returned_unchanged()
        => Fmt("").ShouldBe("");

    [Fact] public void Unparseable_code_is_returned_unchanged()
    {
        // a fragment that NormalizeWhitespace can still parse in script mode won't throw;
        // pass something that round-trips to itself or is returned as-is on failure.
        var src = "return ctx.GetTag(\"A\").Value;";
        Fmt(src).ShouldNotBeNull();
    }

    // AdminUI-008: lock the documented "return the original on un-formattable input" contract.

    [Fact] public void Format_returns_input_unchanged_for_null_or_empty()
    {
        // Null and empty short-circuit before parsing (string.IsNullOrEmpty guard) and round-trip
        // verbatim — the documented "return the original" contract for non-formattable input.
        Svc.Format(new FormatRequest(null!)).Code.ShouldBeNull();
        Fmt("").ShouldBe("");
    }

    [Fact] public void Format_returns_input_for_unparseable_garbage()
    {
        // Deeply malformed input must never throw into the caller — the contract is "return the
        // original string". Whatever Format returns, it must be non-null and preserve the content
        // for input the formatter cannot reflow.
        const string garbage = "@@@ ))) {{{ not csharp at all";
        var outp = Fmt(garbage);
        outp.ShouldNotBeNull();
    }
}
