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

namespace TakeoutSaaS.Application.App.TenantPackages.Handlers;

/// <summary>
/// 获取套餐当前使用租户列表查询处理器。
/// </summary>
public sealed class GetTenantPackageTenantsQueryHandler(ITenantPackageRepository tenantPackageRepository)
    : IRequestHandler<GetTenantPackageTenantsQuery, PagedResult<TenantPackageTenantDto>>
{
    /// <inheritdoc />
    public async Task<PagedResult<TenantPackageTenantDto>> Handle(
        GetTenantPackageTenantsQuery request,
        CancellationToken cancellationToken)
    {
        // 1. 查询套餐使用租户列表
        var (items, totalCount) = await tenantPackageRepository.GetTenantsAsync(
            request.TenantPackageId,
            request.Keyword,
            request.ExpiringWithinDays,
            request.Page,
            request.PageSize,
            cancellationToken);

        // 2. 映射为 DTO
        var dtos = items.Select(t => new TenantPackageTenantDto
        {
            TenantId = t.TenantId,
            Code = t.Code,
            Name = t.Name,
            Status = t.Status,
            ContactName = t.ContactName,
            ContactPhone = t.ContactPhone,
            SubscriptionEffectiveFrom = t.SubscriptionEffectiveFrom,
            SubscriptionEffectiveTo = t.SubscriptionEffectiveTo
        }).ToList();

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