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

namespace TakeoutSaaS.Application.App.Billings.Handlers;

/// <summary>
/// 获取账单详情查询处理器。
/// </summary>
public sealed class GetBillDetailQueryHandler(
    ITenantBillingRepository billingRepository,
    ITenantPaymentRepository paymentRepository,
    ITenantRepository tenantRepository)
    : IRequestHandler<GetBillDetailQuery, BillDetailDto?>
{
    /// <summary>
    /// 处理获取账单详情请求。
    /// </summary>
    /// <param name="request">查询请求。</param>
    /// <param name="cancellationToken">取消标记。</param>
    /// <returns>账单详情或 null。</returns>
    public async Task<BillDetailDto?> Handle(GetBillDetailQuery request, CancellationToken cancellationToken)
    {
        // 1. 查询账单
        var bill = await billingRepository.FindByIdAsync(request.BillId, cancellationToken);
        if (bill is null)
        {
            return null;
        }

        // 2. 查询支付记录
        var payments = await paymentRepository.GetByBillingIdAsync(request.BillId, cancellationToken);

        // 3. 查询租户名称
        var tenant = await tenantRepository.FindByIdAsync(bill.TenantId, cancellationToken);

        // 4. 返回详情 DTO
        return bill.ToDetailDto(payments.ToList(), tenant?.Name);
    }
}
