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

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

public class FormatResolutionTests
{
    private static (Option<string> formatOption, RootCommand root) BuildHarness()
    {
        var formatOption = new Option<string>("--format") { Recursive = true };
        var root = new RootCommand();
        root.Add(formatOption);
        return (formatOption, root);
    }

    [Fact]
    public void ResolveFormat_ExplicitFlag_OverridesConfig()
    {
        var (formatOption, root) = BuildHarness();
        var result = root.Parse(new[] { "--format", "table" });
        var config = new CliConfig { DefaultFormat = "json" };

        var format = CommandHelpers.ResolveFormat(result, formatOption, config);

        Assert.Equal("table", format);
    }

    [Fact]
    public void ResolveFormat_FlagAbsent_UsesConfigDefaultFormat()
    {
        // Regression for CLI-001: when --format is not supplied, the config-file /
        // env-var DefaultFormat must be honoured instead of always falling back to "json".
        var (formatOption, root) = BuildHarness();
        var result = root.Parse(Array.Empty<string>());
        var config = new CliConfig { DefaultFormat = "table" };

        var format = CommandHelpers.ResolveFormat(result, formatOption, config);

        Assert.Equal("table", format);
    }

    [Fact]
    public void ResolveFormat_FlagAbsent_AndNoConfig_DefaultsToJson()
    {
        var (formatOption, root) = BuildHarness();
        var result = root.Parse(Array.Empty<string>());
        var config = new CliConfig { DefaultFormat = "json" };

        var format = CommandHelpers.ResolveFormat(result, formatOption, config);

        Assert.Equal("json", format);
    }
}
