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

namespace Elfisa.Avalonia.ViewModels;

public partial class CartItem : ObservableObject
{
    public PriceItem Source { get; }
    public string Name => Source.DrugName ?? "";
    public string Supplier => Source.SupplierName ?? "";
    public decimal Price => Source.Price;

    [ObservableProperty] private decimal _qty = 1;
    public decimal LineSum => Price * Qty;

    public event Action? Changed;

    public CartItem(PriceItem src) => Source = src;

    partial void OnQtyChanged(decimal value)
    {
        OnPropertyChanged(nameof(LineSum));
        Changed?.Invoke();
    }
}

/// <summary>Единая корзина заказа — общая для «Прайс-листа» и «Отправить».</summary>
public sealed class CartService
{
    public static CartService Instance { get; } = new();

    public ObservableCollection<CartItem> Items { get; } = new();
    public event Action? Changed;

    public decimal Total => Items.Sum(c => c.LineSum);
    public int Count => Items.Count;

    public void Add(PriceItem src, decimal qty = 1)
    {
        if (src is null || string.IsNullOrEmpty(src.SupplierPriceId)) return;
        var existing = Items.FirstOrDefault(c => c.Source.SupplierPriceId == src.SupplierPriceId);
        if (existing != null) existing.Qty += qty;
        else
        {
            var ci = new CartItem(src) { Qty = qty };
            ci.Changed += Raise;
            Items.Add(ci);
        }
        Raise();
    }

    public void Remove(CartItem item)
    {
        if (item is null) return;
        item.Changed -= Raise;
        Items.Remove(item);
        Raise();
    }

    public void Clear()
    {
        foreach (var i in Items) i.Changed -= Raise;
        Items.Clear();
        Raise();
    }

    private void Raise() => Changed?.Invoke();
}
