using MediatR;
using TakeoutSaaS.Application.App.Finance.Invoice.Dto;
using TakeoutSaaS.Application.App.Finance.Invoice.Queries;
using TakeoutSaaS.Domain.Tenants.Repositories;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;
using TakeoutSaaS.Shared.Abstractions.Tenancy;

namespace TakeoutSaaS.Application.App.Finance.Invoice.Handlers;

/// <summary>
/// 发票记录详情查询处理器。
/// </summary>
public sealed class GetFinanceInvoiceRecordDetailQueryHandler(
    ITenantInvoiceRepository repository,
    ITenantProvider tenantProvider)
    : IRequestHandler<GetFinanceInvoiceRecordDetailQuery, FinanceInvoiceRecordDetailDto>
{
    /// <inheritdoc />
    public async Task<FinanceInvoiceRecordDetailDto> Handle(
        GetFinanceInvoiceRecordDetailQuery request,
        CancellationToken cancellationToken)
    {
        var tenantId = tenantProvider.GetCurrentTenantId();
        var record = await repository.FindRecordByIdAsync(tenantId, request.RecordId, cancellationToken)
                     ?? throw new BusinessException(ErrorCodes.NotFound, "发票记录不存在");

        return FinanceInvoiceDtoFactory.ToRecordDetailDto(record);
    }
}
