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

namespace TakeoutSaaS.Application.App.Billings.Handlers;

/// <summary>
/// 获取账单列表查询处理器。
/// </summary>
public sealed class GetBillListQueryHandler(
    ITenantBillingRepository billingRepository,
    ITenantRepository tenantRepository)
    : IRequestHandler<GetBillListQuery, PagedResult<BillDto>>
{
    /// <summary>
    /// 处理获取账单列表请求。
    /// </summary>
    /// <param name="request">查询请求。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>分页账单列表。</returns>
    public async Task<PagedResult<BillDto>> Handle(GetBillListQuery request, CancellationToken cancellationToken)
    {
        // 1. 分页查询账单
        var (bills, total) = await billingRepository.SearchPagedAsync(
            request.TenantId,
            request.Status,
            request.StartDate,
            request.EndDate,
            null,
            null,
            request.Keyword,
            request.PageNumber,
            request.PageSize,
            cancellationToken);

        // 2. 无数据直接返回
        if (bills.Count == 0)
        {
            return new PagedResult<BillDto>([], request.PageNumber, request.PageSize, total);
        }

        // 3. 批量查询租户信息
        var tenantIds = bills.Select(b => b.TenantId).Distinct().ToArray();
        var tenants = await tenantRepository.FindByIdsAsync(tenantIds, cancellationToken);
        var tenantDict = tenants.ToDictionary(t => t.Id, t => t.Name);

        // 4. 映射 DTO
        var result = bills.Select(b => b.ToDto(tenantDict.GetValueOrDefault(b.TenantId))).ToList();

        // 5. 返回分页结果
        return new PagedResult<BillDto>(result, request.PageNumber, request.PageSize, total);
    }
}
