using AdsManagerService.Infrastructure;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace AdsManagerService.API.Controllers;

/// <summary>
/// EN: Handler for getting campaign statistics.
/// VI: Handler lấy thống kê chiến dịch.
/// </summary>
public class GetCampaignStatsQueryHandler : IRequestHandler<GetCampaignStatsQuery, CampaignStatsDto>
{
    private readonly AdsManagerServiceContext _context;

    public GetCampaignStatsQueryHandler(AdsManagerServiceContext context)
    {
        _context = context ?? throw new ArgumentNullException(nameof(context));
    }

    public async Task<CampaignStatsDto> Handle(GetCampaignStatsQuery request, CancellationToken cancellationToken)
    {
        var campaigns = await _context.Campaigns.ToListAsync(cancellationToken);

        return new CampaignStatsDto
        {
            TotalCampaigns = campaigns.Count,
            ActiveCampaigns = campaigns.Count(c => c.Status.Name == "Active"),
            PausedCampaigns = campaigns.Count(c => c.Status.Name == "Paused"),
            DraftCampaigns = campaigns.Count(c => c.Status.Name == "Draft"),
            CompletedCampaigns = campaigns.Count(c => c.Status.Name == "Completed"),
            TotalSpend = campaigns.Sum(c => c.TotalSpend),
            TotalBudget = campaigns.Sum(c => c.Budget.Amount)
        };
    }
}
