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

namespace Elfisa.Avalonia.ViewModels;

public sealed class InvoiceRow
{
    public string Date { get; init; } = "";
    public string Number { get; init; } = "";
    public string Supplier { get; init; } = "";
    public string Location { get; init; } = "";
    public int ItemsCount { get; init; }
    public decimal Sum { get; init; }
}

/// <summary>
/// Накладные — реестр приходных документов. Строится из /api/buyer/report
/// (после деплоя фикса /api/buyer/orders можно перейти на «родной» источник).
/// </summary>
public partial class InvoicesViewModel : ViewModelBase
{
    private readonly ApiClient _api = new();

    public ObservableCollection<InvoiceRow> Rows { get; } = new();

    [ObservableProperty] private bool _busy;
    [ObservableProperty] private string? _status;
    [ObservableProperty] private string _totals = "";

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

    private async Task LoadAsync()
    {
        try
        {
            Busy = true;
            var to = DateTime.Today;
            var from = to.AddMonths(-24);
            var lines = await _api.GetBuyerReportAsync(from, to);

            Rows.Clear();
            foreach (var g in lines.GroupBy(l => l.OrderId)
                         .OrderByDescending(x => x.First().OrderDate ?? DateTime.MinValue))
            {
                var f = g.First();
                Rows.Add(new InvoiceRow
                {
                    Date = f.OrderDate?.ToLocalTime().ToString("dd.MM.yyyy") ?? "",
                    Number = f.GlobalSign ?? "",
                    Supplier = string.Join(", ", g.Select(x => x.Supplier)
                        .Where(s => !string.IsNullOrWhiteSpace(s)).Distinct()),
                    Location = f.Location ?? "",
                    ItemsCount = g.Count(),
                    Sum = g.Sum(x => x.Sum)
                });
            }

            Totals = $"Накладных: {Rows.Count}    Сумма: {Rows.Sum(r => r.Sum):N2}";
            if (Rows.Count == 0) Status = "Накладных за последние 2 года нет.";
        }
        catch (Exception ex) { Status = ex.Message; }
        finally { Busy = false; }
    }
}
