using Scry.Core.Models;
using Scry.Models;

namespace Scry.Services;

public class InMemoryCardRepository : ICardRepository
{
    private readonly List<CollectionEntry> _entries = [];
    private readonly object _lock = new();

    public IReadOnlyList<CollectionEntry> GetAll()
    {
        lock (_lock)
        {
            return _entries.ToList();
        }
    }

    public CollectionEntry? GetById(string id)
    {
        lock (_lock)
        {
            return _entries.FirstOrDefault(e => e.Id == id);
        }
    }

    public void Add(Card card, int quantity = 1, bool isFoil = false)
    {
        lock (_lock)
        {
            // Check if we already have this exact card (same id + foil status)
            var existing = _entries.FirstOrDefault(e =>
                e.Card.Id == card.Id && e.IsFoil == isFoil);

            if (existing != null)
            {
                existing.Quantity += quantity;
            }
            else
            {
                _entries.Add(new CollectionEntry
                {
                    Card = card,
                    Quantity = quantity,
                    IsFoil = isFoil
                });
            }
        }
    }

    public void UpdateQuantity(string entryId, int newQuantity)
    {
        lock (_lock)
        {
            var entry = _entries.FirstOrDefault(e => e.Id == entryId);
            if (entry != null)
            {
                if (newQuantity <= 0)
                {
                    _entries.Remove(entry);
                }
                else
                {
                    entry.Quantity = newQuantity;
                }
            }
        }
    }

    public void Remove(string entryId)
    {
        lock (_lock)
        {
            var entry = _entries.FirstOrDefault(e => e.Id == entryId);
            if (entry != null)
            {
                _entries.Remove(entry);
            }
        }
    }

    public int TotalCards
    {
        get
        {
            lock (_lock)
            {
                return _entries.Sum(e => e.Quantity);
            }
        }
    }

    public int UniqueCards
    {
        get
        {
            lock (_lock)
            {
                return _entries.Count;
            }
        }
    }
}
