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

namespace Application.Features.Api.DonationRank.GetRanking;

internal sealed class Handler(IAppDbContext db) : IQueryHandler<Query, Response>
{
    public async Task<Response> Handle(Query request, CancellationToken ct)
    {
        var list = await db.DonationRanking.AsNoTracking()
            .Where(r => r.ChannelID == request.ChannelID
                     && r.PeriodType == request.PeriodType
                     && r.IsActive
                     && r.Rank <= request.MaxRank)
            .OrderBy(r => r.Rank)
            .Select(r => new RankItem(r.Rank, r.SponsorMemberID, r.SponsorName, r.TotalAmount, r.DonationCount))
            .ToListAsync(ct);

        return new Response(list);
    }
}