using SharepointToolbox.Core.Helpers;

namespace SharepointToolbox.Tests.Helpers;

[Trait("Category", "Unit")]
public class SharePointPaginationHelperTests
{
    [Fact]
    public void BuildPagedViewXml_NullInput_ReturnsViewWithRowLimit()
    {
        var result = SharePointPaginationHelper.BuildPagedViewXml(null, 2000);
        Assert.Equal("<View><RowLimit Paged='TRUE'>2000</RowLimit></View>", result);
    }

    [Fact]
    public void BuildPagedViewXml_EmptyString_ReturnsViewWithRowLimit()
    {
        var result = SharePointPaginationHelper.BuildPagedViewXml("", 2000);
        Assert.Equal("<View><RowLimit Paged='TRUE'>2000</RowLimit></View>", result);
    }

    [Fact]
    public void BuildPagedViewXml_WhitespaceOnly_ReturnsViewWithRowLimit()
    {
        var result = SharePointPaginationHelper.BuildPagedViewXml("   ", 2000);
        Assert.Equal("<View><RowLimit Paged='TRUE'>2000</RowLimit></View>", result);
    }

    [Fact]
    public void BuildPagedViewXml_ExistingRowLimit_Replaces()
    {
        var input = "<View><RowLimit>100</RowLimit></View>";
        var result = SharePointPaginationHelper.BuildPagedViewXml(input, 2000);
        Assert.Equal("<View><RowLimit Paged='TRUE'>2000</RowLimit></View>", result);
    }

    [Fact]
    public void BuildPagedViewXml_ExistingPagedRowLimit_ReplacesWithNewSize()
    {
        var input = "<View><RowLimit Paged='TRUE'>100</RowLimit></View>";
        var result = SharePointPaginationHelper.BuildPagedViewXml(input, 5000);
        Assert.Equal("<View><RowLimit Paged='TRUE'>5000</RowLimit></View>", result);
    }

    [Fact]
    public void BuildPagedViewXml_NoRowLimit_AppendsBeforeClosingView()
    {
        var input = "<View><Query><OrderBy><FieldRef Name='Title'/></OrderBy></Query></View>";
        var result = SharePointPaginationHelper.BuildPagedViewXml(input, 2000);
        Assert.Contains("<RowLimit Paged='TRUE'>2000</RowLimit>", result);
        Assert.EndsWith("</View>", result);
        var rowLimitIndex = result.IndexOf("<RowLimit Paged='TRUE'>2000</RowLimit>", StringComparison.Ordinal);
        var closingViewIndex = result.LastIndexOf("</View>", StringComparison.Ordinal);
        Assert.True(rowLimitIndex < closingViewIndex, "RowLimit should appear before </View>");
    }
}
