using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.SharePoint.Client;
using Moq;
using SharepointToolbox.Core.Models;
using SharepointToolbox.Services;
using SharepointToolbox.ViewModels;
using SharepointToolbox.ViewModels.Tabs;

namespace SharepointToolbox.Tests.ViewModels;

/// <summary>
/// Unit tests for PermissionsViewModel.
/// PERM-02: multi-site scan loop invokes ScanSiteAsync once per URL.
/// </summary>
public class PermissionsViewModelTests
{
    [Fact]
    public async Task StartScanAsync_WithMultipleSiteUrls_CallsServiceOncePerUrl()
    {
        // Arrange
        var mockPermissionsService = new Mock<IPermissionsService>();
        mockPermissionsService
            .Setup(s => s.ScanSiteAsync(
                It.IsAny<ClientContext>(),
                It.IsAny<ScanOptions>(),
                It.IsAny<IProgress<OperationProgress>>(),
                It.IsAny<CancellationToken>()))
            .ReturnsAsync(new List<PermissionEntry>());

        var mockSiteListService = new Mock<ISiteListService>();

        var mockSessionManager = new Mock<ISessionManager>();
        mockSessionManager
            .Setup(s => s.GetOrCreateContextAsync(It.IsAny<TenantProfile>(), It.IsAny<CancellationToken>()))
            .ReturnsAsync((ClientContext)null!);

        var vm = new PermissionsViewModel(
            mockPermissionsService.Object,
            mockSiteListService.Object,
            mockSessionManager.Object,
            new NullLogger<FeatureViewModelBase>());

        // Set up two site URLs via SelectedSites
        vm.SelectedSites.Add(new SiteInfo("https://tenant1.sharepoint.com/sites/alpha", "Alpha"));
        vm.SelectedSites.Add(new SiteInfo("https://tenant1.sharepoint.com/sites/beta", "Beta"));
        vm.SetCurrentProfile(new TenantProfile
        {
            Name = "Test",
            TenantUrl = "https://tenant1.sharepoint.com",
            ClientId = "client-id"
        });

        // Act
        await vm.TestRunOperationAsync(CancellationToken.None, new Progress<OperationProgress>());

        // Assert: ScanSiteAsync called exactly twice (once per URL)
        mockPermissionsService.Verify(
            s => s.ScanSiteAsync(
                It.IsAny<ClientContext>(),
                It.IsAny<ScanOptions>(),
                It.IsAny<IProgress<OperationProgress>>(),
                It.IsAny<CancellationToken>()),
            Times.Exactly(2));
    }
}
