using MediatR;
using TakeoutSaaS.Application.App.Finance.Transactions.Dto;
using TakeoutSaaS.Application.App.Finance.Transactions.Queries;
using TakeoutSaaS.Domain.Finance.Repositories;
using TakeoutSaaS.Shared.Abstractions.Tenancy;

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

/// <summary>
/// 交易流水统计查询处理器。
/// </summary>
public sealed class GetFinanceTransactionStatsQueryHandler(
    IFinanceTransactionRepository financeTransactionRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<GetFinanceTransactionStatsQuery, FinanceTransactionStatsDto>
{
    /// <inheritdoc />
    public async Task<FinanceTransactionStatsDto> Handle(GetFinanceTransactionStatsQuery request, CancellationToken cancellationToken)
    {
        // 1. 读取租户上下文并执行统计查询。
        var tenantId = tenantProvider.GetCurrentTenantId();
        var snapshot = await financeTransactionRepository.GetStatsAsync(
            tenantId,
            request.StoreId,
            request.StartAt,
            request.EndAt,
            request.TransactionType,
            request.DeliveryType,
            request.PaymentMethod,
            request.Keyword,
            cancellationToken);

        // 2. 映射统计结果。
        return new FinanceTransactionStatsDto
        {
            TotalIncome = snapshot.TotalIncome,
            TotalRefund = snapshot.TotalRefund,
            TotalCount = snapshot.TotalCount
        };
    }
}
