using MediatR;
using TakeoutSaaS.Application.App.TenantPackages.Contracts;
using TakeoutSaaS.Application.App.TenantPackages.Queries;
using TakeoutSaaS.Domain.Tenants.Repositories;

namespace TakeoutSaaS.Application.App.TenantPackages.Handlers;

/// <summary>
/// 获取租户套餐使用统计查询处理器。
/// </summary>
public sealed class GetTenantPackageUsagesQueryHandler(ITenantPackageRepository tenantPackageRepository)
    : IRequestHandler<GetTenantPackageUsagesQuery, IReadOnlyList<TenantPackageUsageDto>>
{
    /// <inheritdoc />
    public async Task<IReadOnlyList<TenantPackageUsageDto>> Handle(
        GetTenantPackageUsagesQuery request,
        CancellationToken cancellationToken)
    {
        // 1. 查询套餐使用统计
        var usages = await tenantPackageRepository.GetUsagesAsync(request.TenantPackageIds, cancellationToken);

        // 2. 映射为 DTO
        return usages.Select(u => new TenantPackageUsageDto
        {
            TenantPackageId = u.TenantPackageId,
            ActiveSubscriptionCount = u.ActiveSubscriptionCount,
            ActiveTenantCount = u.ActiveTenantCount,
            TotalSubscriptionCount = u.TotalSubscriptionCount,
            Mrr = u.Mrr,
            Arr = u.Arr,
            ExpiringTenantCount7Days = u.ExpiringTenantCount7Days,
            ExpiringTenantCount15Days = u.ExpiringTenantCount15Days,
            ExpiringTenantCount30Days = u.ExpiringTenantCount30Days
        }).ToList();
    }
}
