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

namespace Application.Features.Api.DonationGoal.GetProgress;

internal sealed class Handler(IAppDbContext db) : IQueryHandler<Query, Response>
{
    public async Task<Response> Handle(Query request, CancellationToken ct)
    {
        var goal = await db.DonationGoalConfig.AsNoTracking().FirstOrDefaultAsync(g => g.ID == request.GoalConfigID && g.ChannelID == request.ChannelID && g.IsActive, ct);
        if (goal is null)
        {
            throw new KeyNotFoundException("목표 설정을 찾을 수 없습니다.");
        }

        var currentAmount = await db.Donation.AsNoTracking()
            .Where(d => d.ChannelID == request.ChannelID
                     && !d.IsTest
                     && (goal.StartAt == null || d.CreatedAt >= goal.StartAt)
                     && (goal.EndAt == null || d.CreatedAt <= goal.EndAt))
            .SumAsync(d => d.Amount, ct);

        var adjusted = currentAmount + goal.StartAmount;
        var percent = goal.TargetAmount > 0 ? Math.Min((decimal)adjusted / goal.TargetAmount * 100, 100) : 0;

        return new Response(goal.ID, goal.Title, goal.StartAmount, goal.TargetAmount, adjusted, Math.Round(percent, 1));
    }
}