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

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

/// <summary>
/// Audit Log #23 (M3): tests for the strongly-typed cached-operation identifier
/// produced by <c>ExternalSystem.CachedCall</c> / <c>Database.CachedWrite</c> and
/// surfaced to scripts via <c>Tracking.Status(id)</c>.
/// </summary>
public class TrackedOperationIdTests
{
    [Fact]
    public void New_ProducesUniqueIds()
    {
        var a = TrackedOperationId.New();
        var b = TrackedOperationId.New();

        Assert.NotEqual(a, b);
        Assert.NotEqual(Guid.Empty, a.Value);
        Assert.NotEqual(Guid.Empty, b.Value);
    }

    [Fact]
    public void Parse_RoundTrip_PreservesValue()
    {
        var original = TrackedOperationId.New();
        var serialized = original.ToString();

        var parsed = TrackedOperationId.Parse(serialized);

        Assert.Equal(original, parsed);
        Assert.Equal(original.Value, parsed.Value);
    }

    [Fact]
    public void TryParse_InvalidInput_ReturnsFalse()
    {
        Assert.False(TrackedOperationId.TryParse("not-a-guid", out var result));
        Assert.Equal(default, result);

        Assert.False(TrackedOperationId.TryParse(null, out var nullResult));
        Assert.Equal(default, nullResult);

        Assert.False(TrackedOperationId.TryParse(string.Empty, out var emptyResult));
        Assert.Equal(default, emptyResult);
    }

    [Fact]
    public void TryParse_ValidInput_ReturnsTrueAndId()
    {
        var original = TrackedOperationId.New();
        var serialized = original.ToString();

        Assert.True(TrackedOperationId.TryParse(serialized, out var parsed));
        Assert.Equal(original, parsed);
    }

    [Fact]
    public void Equality_BasedOnValue()
    {
        var guid = Guid.NewGuid();
        var a = new TrackedOperationId(guid);
        var b = new TrackedOperationId(guid);

        Assert.Equal(a, b);
        Assert.True(a == b);
        Assert.False(a != b);
        Assert.Equal(a.GetHashCode(), b.GetHashCode());
    }

    [Fact]
    public void ToString_StandardGuidFormat()
    {
        var guid = Guid.Parse("12345678-1234-1234-1234-1234567890ab");
        var id = new TrackedOperationId(guid);

        // "D" format: 32 hex digits separated by hyphens (8-4-4-4-12).
        Assert.Equal("12345678-1234-1234-1234-1234567890ab", id.ToString());
    }
}
