using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using OTSSignsOrchestrator.Core.Data;
using OTSSignsOrchestrator.Core.Models.Entities;
using OTSSignsOrchestrator.Core.Services;
using OTSSignsOrchestrator.Desktop.Services;

namespace OTSSignsOrchestrator.Desktop.ViewModels;

/// <summary>
/// ViewModel for viewing and managing Docker Swarm secrets on a remote host.
/// </summary>
public partial class SecretsViewModel : ObservableObject
{
    private readonly IServiceProvider _services;

    [ObservableProperty] private ObservableCollection<SecretListItem> _secrets = new();
    [ObservableProperty] private ObservableCollection<SshHost> _availableHosts = new();
    [ObservableProperty] private SshHost? _selectedSshHost;
    [ObservableProperty] private string _statusMessage = string.Empty;
    [ObservableProperty] private bool _isBusy;

    public SecretsViewModel(IServiceProvider services)
    {
        _services = services;
        _ = LoadHostsAsync();
    }

    private async Task LoadHostsAsync()
    {
        using var scope = _services.CreateScope();
        var db = scope.ServiceProvider.GetRequiredService<XiboContext>();
        var hosts = await db.SshHosts.OrderBy(h => h.Label).ToListAsync();
        AvailableHosts = new ObservableCollection<SshHost>(hosts);
    }

    [RelayCommand]
    private async Task LoadSecretsAsync()
    {
        if (SelectedSshHost == null)
        {
            StatusMessage = "Select an SSH host first.";
            return;
        }

        IsBusy = true;
        try
        {
            var secretsSvc = _services.GetRequiredService<SshDockerSecretsService>();
            secretsSvc.SetHost(SelectedSshHost);

            var items = await secretsSvc.ListSecretsAsync();
            Secrets = new ObservableCollection<SecretListItem>(items);
            StatusMessage = $"Found {items.Count} secret(s) on {SelectedSshHost.Label}.";
        }
        catch (Exception ex)
        {
            StatusMessage = $"Error: {ex.Message}";
        }
        finally
        {
            IsBusy = false;
        }
    }
}
