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

namespace Application.Features.Api.Crew.GetCrewRanking;

internal sealed class Handler(IAppDbContext db) : IQueryHandler<Query, Response>
{
    public async Task<Response> Handle(Query request, CancellationToken ct)
    {
        var session = await db.CrewSession.AsNoTracking()
            .FirstOrDefaultAsync(s => s.ID == request.CrewSessionID, ct);

        if (session is null)
        {
            throw new KeyNotFoundException("세션을 찾을 수 없습니다.");
        }

        var list = await db.CrewDonationSummary.AsNoTracking()
            .Where(s => s.CrewSessionID == request.CrewSessionID)
            .OrderBy(s => s.Rank)
            .Select(s => new CrewRankItem(
                s.Rank,
                s.CrewMemberID,
                s.CrewMember!.Nickname,
                s.CrewMember.Member != null ? s.CrewMember.Member.Thumb : null,
                s.CrewMember.Channel != null ? s.CrewMember.Channel.Name : null,
                s.TotalAmount,
                s.DonationCount,
                s.ContributionRate
            ))
            .ToListAsync(ct);

        return new Response(list, session.TotalAmount);
    }
}