using Application.Abstractions.Data;
using Application.Abstractions.Messaging;
using Domain.Entities.Donations.ValueObject;
using Microsoft.EntityFrameworkCore;

namespace Application.Features.Api.Crew.GetSessionHistory;

internal sealed class Handler(IAppDbContext db) : IQueryHandler<Query, Response>
{
    public async Task<Response> Handle(Query request, CancellationToken ct)
    {
        var query = db.CrewSession.AsNoTracking()
            .Where(s => s.CrewID == request.CrewID && s.Status == CrewSessionStatus.Ended);

        var total = await query.CountAsync(ct);

        var list = await query
            .OrderByDescending(s => s.EndedAt)
            .Skip((request.Page - 1) * request.PerPage)
            .Take(request.PerPage)
            .Select(s => new SessionHistoryItem(
                s.ID, s.Title, s.TotalAmount, s.TotalDonationCount,
                s.StartedAt, s.EndedAt, s.CreatedAt
            ))
            .ToListAsync(ct);

        return new Response(total, list);
    }
}