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

namespace Application.Features.Api.Donation.History;

internal sealed class Handler(IAppDbContext db) : IQueryHandler<Query, Response>
{
    public async Task<Response> Handle(Query request, CancellationToken ct)
    {
        var query = db.Donation.AsNoTracking().Where(d => !d.IsTest);

        query = request.Type switch
        {
            "sent" => query.Where(d => d.SponsorMemberID == request.MemberID),
            "received" => query.Where(d => d.ReceiverMemberID == request.MemberID),
            _ => query.Where(d => d.SponsorMemberID == request.MemberID)
        };

        var total = await query.CountAsync(ct);

        var list = await query
            .OrderByDescending(d => d.CreatedAt)
            .Skip((request.PageNum - 1) * request.PerPage)
            .Take(request.PerPage)
            .Select(d => new DonationItem(
                d.ID,
                d.SponsorMemberID,
                d.SendName,
                d.ReceiverMemberID,
                d.ChannelID,
                d.Channel != null ? d.Channel.Name : "",
                d.Amount,
                d.NetAmount,
                d.Message,
                d.SendName,
                d.CrewMemberID,
                d.CrewMember != null ? d.CrewMember.Nickname : null,
                d.IsTest,
                d.CreatedAt
            ))
            .ToListAsync(ct);

        return new Response(total, list);
    }

}