using Application.Abstractions.Messaging;
using Application.Abstractions.Data;
using Microsoft.EntityFrameworkCore;

namespace Application.Features.Admin.Crypto.Curation.Save;

public sealed class Handler(IAppDbContext db) : ICommandHandler<Command>
{
    public async Task Handle(Command request, CancellationToken ct)
    {
        var coinIDs = request.Items.Select(x => x.CoinID).ToList();
        var coins = await db.Coin.Where(c => coinIDs.Contains(c.ID)).ToListAsync(ct);
        var coinMap = coins.ToDictionary(c => c.ID);

        foreach (var item in request.Items)
        {
            if (!coinMap.TryGetValue(item.CoinID, out var coin))
            {
                continue;
            }

            coin.SetCuration(item.IsFeatured, item.DisplayOrder);
        }

        await db.SaveChangesAsync(ct);
    }
}