using Elfisa.Avalonia.ViewModels;
using Elfisa.Core;
using Xunit;

namespace Elfisa.Tests;

// Все тесты корзины в одном классе → xUnit гонит их последовательно (синглтон CartService).
public class CartServiceTests
{
    private static PriceItem Item(string id, decimal price, string name = "X")
        => new() { SupplierPriceId = id, Price = price, DrugName = name, SupplierName = "S" };

    [Fact]
    public void Add_items_and_total()
    {
        var cart = CartService.Instance;
        cart.Clear();
        cart.Add(Item("1", 10m), 2);
        cart.Add(Item("2", 5m), 3);
        Assert.Equal(2, cart.Count);
        Assert.Equal(35m, cart.Total); // 20 + 15
        cart.Clear();
    }

    [Fact]
    public void Add_same_id_merges_quantity()
    {
        var cart = CartService.Instance;
        cart.Clear();
        cart.Add(Item("1", 10m), 2);
        cart.Add(Item("1", 10m), 3); // тот же supplier_price_id → qty += 3
        Assert.Equal(1, cart.Count);
        Assert.Equal(50m, cart.Total); // qty 5 * 10
        cart.Clear();
    }

    [Fact]
    public void Add_ignores_empty_id()
    {
        var cart = CartService.Instance;
        cart.Clear();
        cart.Add(Item("", 10m), 1);
        Assert.Equal(0, cart.Count);
    }

    [Fact]
    public void Remove_and_clear()
    {
        var cart = CartService.Instance;
        cart.Clear();
        cart.Add(Item("1", 10m), 1);
        cart.Remove(cart.Items[0]);
        Assert.Equal(0, cart.Count);
    }

    [Fact]
    public void Changed_event_fires_on_add()
    {
        var cart = CartService.Instance;
        cart.Clear();
        int fired = 0;
        Action handler = () => fired++;
        cart.Changed += handler;
        cart.Add(Item("1", 10m), 1);
        cart.Changed -= handler;
        cart.Clear();
        Assert.True(fired >= 1);
    }
}
