using System.IO;
using Microsoft.Extensions.Logging.Abstractions;
using Moq;
using SharepointToolbox.Infrastructure.Persistence;
using SharepointToolbox.Services;
using SharepointToolbox.ViewModels;
using SharepointToolbox.ViewModels.Tabs;

namespace SharepointToolbox.Tests.ViewModels;

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

    public SettingsViewModelOwnershipTests()
    {
        _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()
    {
        var settingsService = new SettingsService(new SettingsRepository(_tempFile));
        var mockBranding = new Mock<IBrandingService>().Object;
        var logger = NullLogger<FeatureViewModelBase>.Instance;
        return new SettingsViewModel(settingsService, mockBranding, new ThemeManager(NullLogger<ThemeManager>.Instance), logger);
    }

    [Fact]
    public async Task LoadAsync_AutoTakeOwnership_LoadsFalseByDefault()
    {
        var vm = CreateViewModel();

        await vm.LoadAsync();

        Assert.False(vm.AutoTakeOwnership);
    }

    [Fact]
    public async Task SetAutoTakeOwnership_True_CallsSetAutoTakeOwnershipAsync()
    {
        // Use a real SettingsService backed by temp file to verify persistence
        var settingsService = new SettingsService(new SettingsRepository(_tempFile));
        var mockBranding = new Mock<IBrandingService>().Object;
        var logger = NullLogger<FeatureViewModelBase>.Instance;
        var vm = new SettingsViewModel(settingsService, mockBranding, new ThemeManager(NullLogger<ThemeManager>.Instance), logger);

        await vm.LoadAsync();
        vm.AutoTakeOwnership = true;

        // Small delay to let the fire-and-forget persist
        await Task.Delay(100);

        var persisted = await settingsService.GetSettingsAsync();
        Assert.True(persisted.AutoTakeOwnership);
    }
}
