using System.ComponentModel;
using SharepointToolbox.ViewModels.Dialogs;
using SharepointToolbox.Views.Dialogs;
using Xunit;

namespace SharepointToolbox.Tests.ViewModels.Dialogs;

public class SitePickerDialogLogicTests
{
    private static SitePickerItem Item(string url, string title, long sizeMb = 0, string template = "")
        => new(url, title, sizeMb, 0, template);

    [Fact]
    public void ApplyFilter_TextFilter_MatchesUrlOrTitle_CaseInsensitive()
    {
        var items = new[]
        {
            Item("https://t/sites/hr", "HR Team"),
            Item("https://t/sites/finance", "Finance"),
        };

        var result = SitePickerDialogLogic.ApplyFilter(items, "fINaNce", 0, long.MaxValue, "All").ToList();

        Assert.Single(result);
        Assert.Equal("Finance", result[0].Title);
    }

    [Fact]
    public void ApplyFilter_SizeRange_FiltersInclusively()
    {
        var items = new[]
        {
            Item("a", "A", sizeMb: 100),
            Item("b", "B", sizeMb: 500),
            Item("c", "C", sizeMb: 1200),
        };

        var result = SitePickerDialogLogic.ApplyFilter(items, "", 100, 600, "All").ToList();

        Assert.Equal(2, result.Count);
        Assert.Contains(result, i => i.Title == "A");
        Assert.Contains(result, i => i.Title == "B");
    }

    [Fact]
    public void ApplyFilter_KindAll_SkipsKindCheck()
    {
        var items = new[] { Item("a", "A", template: "STS#3"), Item("b", "B", template: "GROUP#0") };

        var result = SitePickerDialogLogic.ApplyFilter(items, "", 0, long.MaxValue, "All").ToList();

        Assert.Equal(2, result.Count);
    }

    [Fact]
    public void ApplySort_UnknownColumn_ReturnsInputUnchanged()
    {
        var items = new[] { Item("b", "B"), Item("a", "A") };

        var result = SitePickerDialogLogic.ApplySort(items, "Nonexistent", ListSortDirection.Ascending).ToList();

        Assert.Equal("B", result[0].Title);
        Assert.Equal("A", result[1].Title);
    }

    [Fact]
    public void ApplySort_Title_Ascending_And_Descending()
    {
        var items = new[] { Item("b", "B"), Item("a", "A"), Item("c", "C") };

        var asc = SitePickerDialogLogic.ApplySort(items, "Title", ListSortDirection.Ascending).ToList();
        var desc = SitePickerDialogLogic.ApplySort(items, "Title", ListSortDirection.Descending).ToList();

        Assert.Equal(new[] { "A", "B", "C" }, asc.Select(i => i.Title));
        Assert.Equal(new[] { "C", "B", "A" }, desc.Select(i => i.Title));
    }

    [Theory]
    [InlineData("", 42L, 42L)]
    [InlineData("   ", 42L, 42L)]
    [InlineData("not-a-number", 42L, 42L)]
    [InlineData("100", 42L, 100L)]
    [InlineData("  100  ", 42L, 100L)]
    public void ParseLongOrDefault_HandlesEmptyAndInvalid(string input, long fallback, long expected)
    {
        Assert.Equal(expected, SitePickerDialogLogic.ParseLongOrDefault(input, fallback));
    }
}
