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, total) = await tenantRepository.SearchPagedAsync(
            request.Status,
            request.VerificationStatus,
            request.Name,
            request.ContactName,
            request.ContactPhone,
            request.Keyword,
            request.Page,
            request.PageSize,
            cancellationToken);

        // 2. (空行后) 无数据直接返回
        if (tenants.Count == 0)
        {
            return new PagedResult<TenantDto>([], request.Page, request.PageSize, total);
        }

        // 3. (空行后) 批量查询订阅与实名资料（避免 N+1）
        var tenantIds = tenants.Select(x => x.Id).ToArray();
        var subscriptions = await tenantRepository.GetSubscriptionsAsync(tenantIds, cancellationToken);
        var verifications = await tenantRepository.GetVerificationProfilesAsync(tenantIds, cancellationToken);

        // 4. (空行后) 构建订阅与实名资料映射
        var subscriptionByTenantId = subscriptions
            .GroupBy(x => x.TenantId)
            .ToDictionary(x => x.Key, x => x.FirstOrDefault());
        var verificationByTenantId = verifications.ToDictionary(x => x.TenantId);

        // 5. (空行后) 映射 DTO（带订阅与认证）
        var result = new List<TenantDto>(tenants.Count);
        foreach (var tenant in tenants)
        {
            subscriptionByTenantId.TryGetValue(tenant.Id, out var subscription);
            verificationByTenantId.TryGetValue(tenant.Id, out var verification);
            result.Add(TenantMapping.ToDto(tenant, subscription, verification));
        }

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