using MediatR;
using TakeoutSaaS.Application.App.Statistics.Dto;
using TakeoutSaaS.Application.App.Statistics.Queries;
using TakeoutSaaS.Domain.Tenants.Repositories;

namespace TakeoutSaaS.Application.App.Statistics.Handlers;

/// <summary>
/// 获取配额使用排行处理器。
/// </summary>
public sealed class GetQuotaUsageRankingQueryHandler(IStatisticsRepository statisticsRepository)
    : IRequestHandler<GetQuotaUsageRankingQuery, QuotaUsageRankingDto>
{
    /// <inheritdoc />
    public async Task<QuotaUsageRankingDto> Handle(GetQuotaUsageRankingQuery request, CancellationToken cancellationToken)
    {
        // 查询指定类型的配额使用排行
        var items = await statisticsRepository.GetQuotaUsageRankingAsync(
            request.QuotaType,
            request.TopN,
            cancellationToken);

        // 映射为 DTO
        var rankings = items.Select(x => new QuotaUsageRankItem
        {
            TenantId = x.TenantId.ToString(),
            TenantName = x.TenantName,
            UsedValue = x.UsedValue,
            LimitValue = x.LimitValue,
            UsagePercentage = x.UsagePercentage
        }).ToList();

        return new QuotaUsageRankingDto
        {
            QuotaType = request.QuotaType,
            Rankings = rankings
        };
    }
}
