using System.IO;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
using SharepointToolbox.Core.Models;
using SharepointToolbox.Infrastructure.Persistence;
using SharepointToolbox.Services;
using SharepointToolbox.ViewModels;
using SharepointToolbox.ViewModels.Tabs;

namespace SharepointToolbox.Tests.ViewModels;

[Trait("Category", "Unit")]
public class SettingsViewModelLogoTests : IDisposable
{
    private readonly string _tempFile;

    public SettingsViewModelLogoTests()
    {
        _tempFile = Path.GetTempFileName();
        File.Delete(_tempFile);
    }

    public void Dispose()
    {
        if (File.Exists(_tempFile)) File.Delete(_tempFile);
        if (File.Exists(_tempFile + ".tmp")) File.Delete(_tempFile + ".tmp");
    }

    private SettingsViewModel CreateViewModel(IBrandingService? brandingService = null)
    {
        var settingsService = new SettingsService(new SettingsRepository(_tempFile));
        var mockBranding = brandingService ?? new Mock<IBrandingService>().Object;
        var logger = NullLogger<FeatureViewModelBase>.Instance;
        return new SettingsViewModel(settingsService, mockBranding, new ThemeManager(NullLogger<ThemeManager>.Instance), logger);
    }

    [Fact]
    public void Constructor_BrowseMspLogoCommand_IsNotNull()
    {
        var vm = CreateViewModel();
        Assert.NotNull(vm.BrowseMspLogoCommand);
    }

    [Fact]
    public void Constructor_ClearMspLogoCommand_IsNotNull()
    {
        var vm = CreateViewModel();
        Assert.NotNull(vm.ClearMspLogoCommand);
    }

    [Fact]
    public void Constructor_MspLogoPreview_IsNullByDefault()
    {
        var vm = CreateViewModel();
        Assert.Null(vm.MspLogoPreview);
    }

    [Fact]
    public async Task ClearMspLogoCommand_CallsClearMspLogoAsync_AndSetsMspLogoPreviewToNull()
    {
        var mockBranding = new Mock<IBrandingService>();
        mockBranding.Setup(b => b.ClearMspLogoAsync()).Returns(Task.CompletedTask);

        var vm = CreateViewModel(mockBranding.Object);

        await vm.ClearMspLogoCommand.ExecuteAsync(null);

        mockBranding.Verify(b => b.ClearMspLogoAsync(), Times.Once);
        Assert.Null(vm.MspLogoPreview);
    }
}
