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

namespace TakeoutSaaS.Application.App.Tenants.Handlers;

/// <summary>
/// 租户分页查询处理器。
/// </summary>
public sealed class SearchTenantsQueryHandler(ITenantRepository tenantRepository)
    : IRequestHandler<SearchTenantsQuery, PagedResult<TenantDto>>
{
    /// <inheritdoc />
    public async Task<PagedResult<TenantDto>> Handle(SearchTenantsQuery request, CancellationToken cancellationToken)
    {
        // 1. 查询租户列表
        var tenants = await tenantRepository.SearchAsync(request.Status, request.Keyword, cancellationToken);
        var total = tenants.Count;

        // 2. 分页
        var paged = tenants
            .Skip((request.Page - 1) * request.PageSize)
            .Take(request.PageSize)
            .ToList();

        // 3. 映射 DTO（带订阅与认证）
        var result = new List<TenantDto>(paged.Count);
        foreach (var tenant in paged)
        {
            var subscription = await tenantRepository.GetActiveSubscriptionAsync(tenant.Id, cancellationToken);
            var verification = await tenantRepository.GetVerificationProfileAsync(tenant.Id, cancellationToken);
            result.Add(TenantMapping.ToDto(tenant, subscription, verification));
        }

        // 4. 返回分页结果
        return new PagedResult<TenantDto>(result, request.Page, request.PageSize, total);
    }
}
