using System;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Elfisa.Core;

namespace Elfisa.Avalonia.ViewModels;

public partial class LoginViewModel : ViewModelBase
{
    private readonly Action _onSuccess;
    private readonly ApiClient _api = new();

    [ObservableProperty] private string _username = "";
    [ObservableProperty] private string _password = "";
    [ObservableProperty] private string? _error;
    [ObservableProperty] private bool _busy;

    public LoginViewModel(Action onSuccess) => _onSuccess = onSuccess;

    [RelayCommand]
    private async Task LoginAsync()
    {
        Error = null;
        if (string.IsNullOrWhiteSpace(Username) || string.IsNullOrWhiteSpace(Password))
        {
            Error = "Введите логин и пароль.";
            return;
        }

        try
        {
            Busy = true;
            var resp = await _api.LoginAsync(Username.Trim(), Password);
            Session.Current.Token = resp.Token;
            Session.Current.Role = resp.Role;
            Session.Current.Username = Username.Trim();
            _onSuccess();
        }
        catch (ApiException ex) { Error = ex.Message; }
        catch (Exception ex) { Error = "Не удалось войти: " + ex.Message; }
        finally { Busy = false; }
    }
}
