using System.Globalization;
using ZB.MOM.WW.ScadaBridge.Commons.Types;

namespace ZB.MOM.WW.ScadaBridge.Commons.Tests.Types;

/// <summary>
/// Tests for <see cref="ValueFormatter"/>. Includes the Commons-012 regression:
/// formatting must be culture-invariant because the formatter feeds non-UI contexts
/// (gRPC stream events, logs) where locale-dependent output would be inconsistent.
/// </summary>
public class ValueFormatterTests
{
    [Fact]
    public void FormatDisplayValue_Null_ReturnsEmptyString()
    {
        Assert.Equal("", ValueFormatter.FormatDisplayValue(null));
    }

    [Fact]
    public void FormatDisplayValue_String_ReturnsValueUnchanged()
    {
        Assert.Equal("hello", ValueFormatter.FormatDisplayValue("hello"));
    }

    [Fact]
    public void FormatDisplayValue_Collection_JoinsWithComma()
    {
        Assert.Equal("1,2,3", ValueFormatter.FormatDisplayValue(new[] { 1, 2, 3 }));
    }

    // ── Commons-012 regression: culture-invariant numeric/date formatting ──

    [Fact]
    public void FormatDisplayValue_Double_UsesInvariantCulture_RegardlessOfThreadCulture()
    {
        var original = CultureInfo.CurrentCulture;
        try
        {
            // German uses a comma as the decimal separator; invariant uses a dot.
            CultureInfo.CurrentCulture = new CultureInfo("de-DE");
            Assert.Equal("3.14", ValueFormatter.FormatDisplayValue(3.14));
        }
        finally
        {
            CultureInfo.CurrentCulture = original;
        }
    }

    [Fact]
    public void FormatDisplayValue_DateTime_UsesInvariantCulture_RegardlessOfThreadCulture()
    {
        var original = CultureInfo.CurrentCulture;
        try
        {
            CultureInfo.CurrentCulture = new CultureInfo("de-DE");
            var dt = new DateTime(2026, 5, 16, 0, 0, 0, DateTimeKind.Utc);
            var invariant = dt.ToString(CultureInfo.InvariantCulture);
            Assert.Equal(invariant, ValueFormatter.FormatDisplayValue(dt));
        }
        finally
        {
            CultureInfo.CurrentCulture = original;
        }
    }

    [Fact]
    public void FormatDisplayValue_CollectionOfDoubles_UsesInvariantCulture()
    {
        var original = CultureInfo.CurrentCulture;
        try
        {
            CultureInfo.CurrentCulture = new CultureInfo("de-DE");
            Assert.Equal("1.5,2.5", ValueFormatter.FormatDisplayValue(new[] { 1.5, 2.5 }));
        }
        finally
        {
            CultureInfo.CurrentCulture = original;
        }
    }
}
