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

namespace Application.Features.Api.Studio.Settlement.GetTax;

internal sealed class Handler(IAppDbContext db) : IQueryHandler<Query, Result<Response>>
{
    public async Task<Result<Response>> Handle(Query request, CancellationToken ct)
    {
        var monthlyRaw = await db.WithdrawalRequest.AsNoTracking()
            .Where(w => w.MemberID == request.MemberID && w.Status == WithdrawalStatus.Completed && w.RequestedAt.Year == request.Year)
            .GroupBy(w => w.RequestedAt.Month)
            .Select(g => new
            {
                Month = g.Key,
                GrossAmount = g.Sum(w => w.RequestedAmount),
                IncomeTax = g.Sum(w => w.IncomeTax),
                LocalTax = g.Sum(w => w.LocalTax),
                NetAmount = g.Sum(w => w.NetAmount),
                PaymentCount = g.Count()
            })
            .OrderByDescending(x => x.Month)
            .ToListAsync(ct);

        var monthlyList = monthlyRaw.Select(m => new MonthItem(m.Month, m.GrossAmount, m.IncomeTax, m.LocalTax, m.NetAmount, m.PaymentCount)).ToList();

        var annualSummary = new AnnualSummary(
            monthlyList.Sum(m => m.GrossAmount),
            monthlyList.Sum(m => m.IncomeTax),
            monthlyList.Sum(m => m.LocalTax),
            monthlyList.Sum(m => m.NetAmount)
        );

        return Result.Success(new Response(request.Year, annualSummary, monthlyList));
    }
}