using System;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using Elfisa.Core;

namespace Elfisa.Avalonia.ViewModels;

/// <summary>Справочник покупателя: профиль + грузополучатели (адреса).</summary>
public partial class DirectoryViewModel : ViewModelBase
{
    private readonly ApiClient _api = new();

    public string UserName => Session.Current.Username ?? "";
    public string RoleLabel => Session.Current.Role switch
    {
        "buyer" => "Покупатель",
        "supplier" => "Поставщик",
        "manager" => "Менеджер",
        "admin" => "Администратор",
        _ => Session.Current.Role ?? ""
    };

    public ObservableCollection<BuyerLocationDto> Locations { get; } = new();

    [ObservableProperty] private bool _busy;
    [ObservableProperty] private string? _status;

    public DirectoryViewModel()
    {
        _api.SetToken(Session.Current.Token);
        if (Session.Current.IsAuthenticated) _ = LoadAsync();
    }

    private async Task LoadAsync()
    {
        try
        {
            Busy = true;
            var locs = await _api.GetBuyerLocationsAsync();
            Locations.Clear();
            foreach (var l in locs) Locations.Add(l);
            if (Locations.Count == 0) Status = "Грузополучатели не заданы.";
        }
        catch (Exception ex) { Status = ex.Message; }
        finally { Busy = false; }
    }
}
