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

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

/// <summary>
/// Verifies the CSV parsing + entry-mapping behaviour that backs
/// <c>instance native-alarm-source import</c>: parse errors block the apply step;
/// valid CSV produces the <see cref="NativeAlarmSourceOverrideEntry"/> list the
/// <see cref="SetInstanceNativeAlarmSourceOverridesCommand"/> consumes.
/// </summary>
public class ImportNativeAlarmSourceOverridesTests
{
    // ── error path ───────────────────────────────────────────────────────────

    [Fact]
    public void CsvWithMissingHeader_ProducesErrors()
    {
        var result = NativeAlarmSourceOverrideCsvParser.Parse("Pressure,ConnA,ref,Active");

        Assert.NotEmpty(result.Errors);
        Assert.Empty(result.Rows);
    }

    [Fact]
    public void CsvWithBlankSourceName_ProducesError()
    {
        const string csv = "SourceName,Connection,SourceReference,Filter\n,ConnA,ref,Active";
        var result = NativeAlarmSourceOverrideCsvParser.Parse(csv);

        Assert.NotEmpty(result.Errors);
        Assert.Empty(result.Rows);
    }

    // ── happy path ───────────────────────────────────────────────────────────

    [Fact]
    public void ValidCsv_ProducesCorrectEntryList()
    {
        const string csv = """
            SourceName,Connection,SourceReference,Filter
            Pressure,ConnA,ns=2;s=Pump,Active
            Temp,,,
            """;

        var parseResult = NativeAlarmSourceOverrideCsvParser.Parse(csv);

        Assert.Empty(parseResult.Errors);
        Assert.Equal(2, parseResult.Rows.Count);

        // Build the same entry list that the CLI import action produces.
        var entries = parseResult.Rows
            .Select(r => new NativeAlarmSourceOverrideEntry(
                r.SourceName, r.Connection, r.SourceReference, r.Filter))
            .ToList();

        Assert.Equal("Pressure", entries[0].SourceCanonicalName);
        Assert.Equal("ConnA", entries[0].ConnectionNameOverride);
        Assert.Equal("ns=2;s=Pump", entries[0].SourceReferenceOverride);
        Assert.Equal("Active", entries[0].ConditionFilterOverride);

        // All-blank override fields → inherited (null) on every field.
        Assert.Equal("Temp", entries[1].SourceCanonicalName);
        Assert.Null(entries[1].ConnectionNameOverride);
        Assert.Null(entries[1].SourceReferenceOverride);
        Assert.Null(entries[1].ConditionFilterOverride);
    }
}
