using ZB.MOM.WW.ScadaBridge.CLI;
using ZB.MOM.WW.ScadaBridge.CLI.Commands;

namespace ZB.MOM.WW.ScadaBridge.CLI.Tests;

/// <summary>
/// Regression tests for CLI-002 (empty success body) and CLI-003 (non-JSON success
/// body) — both previously crashed table rendering with an unhandled exception.
/// </summary>
[Collection("Console")]
public class ResponseRenderingTests
{
    [Fact]
    public void HandleResponse_EmptyBody_TableFormat_DoesNotThrow_ReturnsZero()
    {
        // CLI-002: a 200/204 with an empty body must be treated as "succeeded, no output".
        var writer = new StringWriter();
        Console.SetOut(writer);

        try
        {
            var response = new ManagementResponse(204, "", null, null);
            var exitCode = CommandHelpers.HandleResponse(response, "table");

            Assert.Equal(0, exitCode);
        }
        finally
        {
            Console.SetOut(new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = true });
        }
    }

    [Fact]
    public void HandleResponse_EmptyBody_JsonFormat_DoesNotThrow_ReturnsZero()
    {
        var writer = new StringWriter();
        Console.SetOut(writer);

        try
        {
            var response = new ManagementResponse(200, "   ", null, null);
            var exitCode = CommandHelpers.HandleResponse(response, "json");

            Assert.Equal(0, exitCode);
        }
        finally
        {
            Console.SetOut(new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = true });
        }
    }

    [Fact]
    public void HandleResponse_NonJsonBody_TableFormat_FallsBackToRaw_ReturnsZero()
    {
        // CLI-003: a success status with a non-JSON body (e.g. proxy HTML error page)
        // must not crash; it should print the raw body verbatim.
        var writer = new StringWriter();
        Console.SetOut(writer);

        try
        {
            var response = new ManagementResponse(200, "<html>Service Unavailable</html>", null, null);
            var exitCode = CommandHelpers.HandleResponse(response, "table");

            Assert.Equal(0, exitCode);
            Assert.Contains("<html>Service Unavailable</html>", writer.ToString());
        }
        finally
        {
            Console.SetOut(new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = true });
        }
    }
}
