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

namespace TakeoutSaaS.Application.App.Tenants.Handlers;

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

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