using AsadiTools.Models;
using System.Text.Json;

namespace AsadiTools.Services;

public class CartService(IHttpContextAccessor httpContextAccessor)
{
    private const string SessionKey = "Cart";
    private ISession Session => httpContextAccessor.HttpContext!.Session;

    public List<CartItem> GetItems()
    {
        var json = Session.GetString(SessionKey);
        return json is null ? [] : JsonSerializer.Deserialize<List<CartItem>>(json) ?? [];
    }

    public void AddItem(CartItem item)
    {
        var items = GetItems();
        var existing = items.FirstOrDefault(i => i.ProductId == item.ProductId);
        if (existing is not null)
            existing.Qty++;
        else
            items.Add(item);
        Save(items);
    }

    public void UpdateQty(int productId, int qty)
    {
        var items = GetItems();
        var item = items.FirstOrDefault(i => i.ProductId == productId);
        if (item is null) return;
        if (qty <= 0) items.Remove(item);
        else item.Qty = qty;
        Save(items);
    }

    public void RemoveItem(int productId)
    {
        var items = GetItems().Where(i => i.ProductId != productId).ToList();
        Save(items);
    }

    public void Clear() => Session.Remove(SessionKey);

    public int Count => GetItems().Sum(i => i.Qty);
    public decimal Total => GetItems().Sum(i => i.Subtotal);

    private void Save(List<CartItem> items) =>
        Session.SetString(SessionKey, JsonSerializer.Serialize(items));
}
