using Microsoft.EntityFrameworkCore;
using SVSim.Database;
using SVSim.Database.Enums;
using SVSim.Database.Models;

namespace SVSim.EmulatedEntrypoint.Services;

public class DbCardPoolProvider : ICardPoolProvider
{
    private readonly SVSimDbContext _db;
    public DbCardPoolProvider(SVSimDbContext db) { _db = db; }

    public IReadOnlyList<ShadowverseCardEntry> GetPool(PackConfigEntry pack)
    {
        switch (pack.PackCategory)
        {
            case PackCategory.None:
            case PackCategory.LegendCardPack:
            {
                var pool = _db.CardSets
                    .Where(s => s.Id == pack.BasePackId)
                    .SelectMany(s => s.Cards)
                    .Where(c => !c.IsFoil)
                    .ToList();
                if (pool.Count > 0) return pool;

                // BasePackId 90001 (and the 9xxxx range generally) is a synthetic "Throwback
                // Rotation" category that doesn't have a corresponding real card_set in the
                // prod card master — its real pool is a curated subset of rotation-eligible
                // older sets (Altersphere–Colosseum for 99047; see the gacha_detail string).
                // We don't have that membership map, so fall back to all in-rotation cards.
                // Broader pool than prod but produces a valid 8-card draw, which is what the
                // tutorial flow needs to advance to step 100.
                // TODO: import the real Throwback Rotation card-set membership and key the
                // pool off that. Source data is in the client's pack-pool master, not yet
                // captured.
                return _db.CardSets
                    .Where(s => s.IsInRotation)
                    .SelectMany(s => s.Cards)
                    .Where(c => !c.IsFoil)
                    .Distinct()
                    .ToList();
            }

            case PackCategory.SpecialCardPack:
            case PackCategory.LimitedSpecialCardPack:
                return _db.CardSets
                    .Where(s => s.IsInRotation)
                    .SelectMany(s => s.Cards)
                    .Where(c => !c.IsFoil)
                    .Distinct()
                    .ToList();

            default:
                return Array.Empty<ShadowverseCardEntry>();
        }
    }

    public ShadowverseCardEntry? TryGetFoilTwin(long baseCardId) =>
        _db.Cards.FirstOrDefault(c => c.Id == baseCardId + 1 && c.IsFoil);
}
