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

namespace Application.Features.Api.Crew.GetActiveSession;

internal sealed class Handler(IAppDbContext db) : IQueryHandler<Query, Response?>
{
    public async Task<Response?> Handle(Query request, CancellationToken ct)
    {
        var session = await db.CrewSession.AsNoTracking()
            .Include(s => s.Consents).ThenInclude(c => c.CrewMember)
            .Include(s => s.Summaries).ThenInclude(s => s.CrewMember)
            .Where(s => s.CrewID == request.CrewID && s.Status != CrewSessionStatus.Ended)
            .FirstOrDefaultAsync(ct);

        if (session is null) return null;

        var consents = session.Consents.Select(c => new ConsentItem(
            c.CrewMemberID,
            c.CrewMember?.Nickname ?? "",
            c.IsConsented,
            c.ConsentedAt
        )).ToList();

        var summaries = session.Summaries
            .OrderBy(s => s.Rank)
            .Select(s => new SummaryItem(
                s.CrewMemberID,
                s.CrewMember?.Nickname ?? "",
                s.TotalAmount,
                s.DonationCount,
                s.ContributionRate,
                s.Rank
            )).ToList();

        return new Response(
            session.ID, session.Title, session.Status.ToString(),
            session.StartedAt, session.CreatedAt,
            session.TotalAmount, session.TotalDonationCount,
            consents, summaries
        );
    }
}