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

namespace TakeoutSaaS.Application.App.QuotaPackages.Handlers;

/// <summary>
/// 获取租户配额购买记录查询处理器。
/// </summary>
public sealed class GetTenantQuotaPurchasesQueryHandler(IQuotaPackageRepository quotaPackageRepository)
    : IRequestHandler<GetTenantQuotaPurchasesQuery, PagedResult<TenantQuotaPurchaseDto>>
{
    /// <inheritdoc />
    public async Task<PagedResult<TenantQuotaPurchaseDto>> Handle(GetTenantQuotaPurchasesQuery request, CancellationToken cancellationToken)
    {
        // 1. 分页查询购买记录
        var (items, total) = await quotaPackageRepository.GetPurchasesPagedAsync(
            request.TenantId,
            request.Page,
            request.PageSize,
            cancellationToken);

        // 2. 映射为 DTO
        var dtos = items.Select(x => new TenantQuotaPurchaseDto
        {
            Id = x.Purchase.Id,
            TenantId = x.Purchase.TenantId,
            QuotaPackageId = x.Purchase.QuotaPackageId,
            QuotaPackageName = x.Package.Name,
            QuotaType = x.Package.QuotaType,
            QuotaValue = x.Purchase.QuotaValue,
            Price = x.Purchase.Price,
            PurchasedAt = x.Purchase.PurchasedAt,
            ExpiredAt = x.Purchase.ExpiredAt,
            Notes = x.Purchase.Notes
        }).ToList();

        // 3. 返回分页结果
        return new PagedResult<TenantQuotaPurchaseDto>(dtos, request.Page, request.PageSize, total);
    }
}
