using ClawdDotNet.Core.Backup;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;

namespace ClawdDotNet.Desktop.ViewModels;

public sealed record RestoreResultData(string TargetDirectory, string? Passphrase, bool Overwrite);

public sealed partial class RestoreBackupViewModel : ViewModelBase
{
    private readonly BackupManifest _manifest;

    public string InstanceName => _manifest.InstanceName;
    public DateTime CreatedAt => _manifest.CreatedAt;
    public int FileCount => _manifest.Files.Count;
    public bool NeedsPassphrase => _manifest.HasSecrets;

    public string SecretsDescription => _manifest.HasSecrets
        ? $"{_manifest.SecretCount}, mit Passphrase geschützt"
        : _manifest.SecretCount > 0
            ? $"{_manifest.SecretCount} entfernt"
            : "keine";

    [ObservableProperty]
    private string _targetDirectory = "";

    [ObservableProperty]
    private string _passphrase = "";

    [ObservableProperty]
    private bool _overwrite;

    [ObservableProperty]
    private string _statusMessage = "";

    public RestoreResultData? Result { get; private set; }

    public event Action? CloseRequested;

    public RestoreBackupViewModel() : this(new BackupManifest(), @"C:\Instance_Restored") { }

    public RestoreBackupViewModel(BackupManifest manifest, string suggestedTarget)
    {
        _manifest = manifest;
        TargetDirectory = suggestedTarget;
    }

    [RelayCommand]
    private void Confirm()
    {
        if (string.IsNullOrWhiteSpace(TargetDirectory))
        {
            StatusMessage = "Bitte einen Zielordner angeben.";
            return;
        }

        if (NeedsPassphrase && string.IsNullOrEmpty(Passphrase))
        {
            StatusMessage = "Bitte Passphrase für geschützte Zugangsdaten eingeben.";
            return;
        }

        Result = new RestoreResultData(
            TargetDirectory.Trim(),
            NeedsPassphrase ? Passphrase : null,
            Overwrite);

        CloseRequested?.Invoke();
    }

    [RelayCommand]
    private void Cancel()
    {
        Result = null;
        CloseRequested?.Invoke();
    }
}
