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

namespace TakeoutSaaS.Application.App.Tenants.Handlers;

/// <summary>
/// 获取租户列表查询处理器。
/// </summary>
public sealed class ListTenantsQueryHandler(ITenantRepository tenantRepository)
    : IRequestHandler<ListTenantsQuery, PagedResult<TenantListItemDto>>
{
    /// <inheritdoc />
    public async Task<PagedResult<TenantListItemDto>> Handle(ListTenantsQuery request, CancellationToken cancellationToken)
    {
        // 1. 查询租户列表
        var tenants = await tenantRepository.GetAllAsync(request.Keyword, cancellationToken);

        // 2. 计算分页参数
        var totalCount = tenants.Count;
        var page = Math.Max(1, request.Page);
        var pageSize = Math.Clamp(request.PageSize, 1, 100);

        // 3. 应用分页
        var pagedTenants = tenants
            .Skip((page - 1) * pageSize)
            .Take(pageSize)
            .ToArray();

        // 4. 映射 DTO
        var dtos = pagedTenants.Select(t => new TenantListItemDto
        {
            Id = t.Id,
            Code = t.Code,
            Name = t.Name,
            ShortName = t.ShortName,
            ContactName = t.ContactName,
            ContactPhone = t.ContactPhone,
            Status = t.Status,
            VerificationStatus = TenantVerificationStatus.Approved, // TODO: 从认证表查询
            EffectiveTo = t.EffectiveTo
        }).ToArray();

        // 5. 返回分页结果
        return new PagedResult<TenantListItemDto>(dtos, page, pageSize, totalCount);
    }
}
