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

namespace TakeoutSaaS.Application.App.QuotaPackages.Handlers;

/// <summary>
/// 获取租户配额使用情况查询处理器。
/// </summary>
public sealed class GetTenantQuotaUsageQueryHandler(IQuotaPackageRepository quotaPackageRepository)
    : IRequestHandler<GetTenantQuotaUsageQuery, IReadOnlyList<TenantQuotaUsageDto>>
{
    /// <inheritdoc />
    public async Task<IReadOnlyList<TenantQuotaUsageDto>> Handle(GetTenantQuotaUsageQuery request, CancellationToken cancellationToken)
    {
        // 1. 查询配额使用情况
        var items = await quotaPackageRepository.GetUsageByTenantAsync(
            request.TenantId,
            request.QuotaType,
            cancellationToken);

        // 2. 映射为 DTO
        return items.Select(x => new TenantQuotaUsageDto
        {
            TenantId = x.TenantId,
            QuotaType = x.QuotaType,
            LimitValue = x.LimitValue,
            UsedValue = x.UsedValue,
            RemainingValue = x.LimitValue - x.UsedValue,
            ResetCycle = x.ResetCycle,
            LastResetAt = x.LastResetAt
        }).ToList();
    }
}
