using AdsServingService.Infrastructure;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace AdsServingService.API.Application.Queries;

/// <summary>
/// EN: Handler for GetBudgetPacersQuery.
/// VI: Handler cho GetBudgetPacersQuery.
/// </summary>
public class GetBudgetPacersQueryHandler : IRequestHandler<GetBudgetPacersQuery, PagedResult<BudgetPacerDto>>
{
    private readonly AdsServingServiceContext _context;

    public GetBudgetPacersQueryHandler(AdsServingServiceContext context)
    {
        _context = context ?? throw new ArgumentNullException(nameof(context));
    }

    public async Task<PagedResult<BudgetPacerDto>> Handle(GetBudgetPacersQuery request, CancellationToken cancellationToken)
    {
        var query = _context.BudgetPacers.AsQueryable();

        // Apply filters
        if (request.CampaignId.HasValue)
            query = query.Where(bp => EF.Property<Guid>(bp, "_campaignId") == request.CampaignId.Value);

        // Get total count
        var totalCount = await query.CountAsync(cancellationToken);

        // Apply pagination
        var pacers = await query
            .OrderByDescending(bp => EF.Property<DateTime>(bp, "_lastUpdated"))
            .Skip((request.Page - 1) * request.PageSize)
            .Take(request.PageSize)
            .Select(bp => new BudgetPacerDto
            {
                Id = bp.Id,
                CampaignId = EF.Property<Guid>(bp, "_campaignId"),
                DailyBudget = EF.Property<decimal>(bp, "_dailyBudget"),
                SpentToday = EF.Property<decimal>(bp, "_spentToday"),
                RemainingBudget = bp.RemainingBudget,
                UtilizationPercent = bp.UtilizationPercent,
                Strategy = bp.Strategy.ToString(),
                LastUpdated = EF.Property<DateTime>(bp, "_lastUpdated")
            })
            .ToListAsync(cancellationToken);

        return new PagedResult<BudgetPacerDto>
        {
            Items = pacers,
            TotalCount = totalCount,
            Page = request.Page,
            PageSize = request.PageSize
        };
    }
}
