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 SearchFinanceTransactionListQueryHandler(
    IFinanceTransactionRepository financeTransactionRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<SearchFinanceTransactionListQuery, FinanceTransactionListResultDto>
{
    /// <inheritdoc />
    public async Task<FinanceTransactionListResultDto> Handle(SearchFinanceTransactionListQuery request, CancellationToken cancellationToken)
    {
        // 1. 读取租户上下文并执行分页查询。
        var tenantId = tenantProvider.GetCurrentTenantId();
        var page = Math.Max(1, request.Page);
        var pageSize = Math.Clamp(request.PageSize, 1, 200);

        var snapshot = await financeTransactionRepository.SearchPageAsync(
            tenantId,
            request.StoreId,
            request.StartAt,
            request.EndAt,
            request.TransactionType,
            request.DeliveryType,
            request.PaymentMethod,
            request.Keyword,
            page,
            pageSize,
            cancellationToken);

        // 2. 映射结果并返回。
        return new FinanceTransactionListResultDto
        {
            Items = snapshot.Items.Select(FinanceTransactionMapping.ToListItem).ToList(),
            Total = snapshot.TotalCount,
            Page = page,
            PageSize = pageSize,
            PageIncomeAmount = snapshot.PageIncomeAmount,
            PageRefundAmount = snapshot.PageRefundAmount
        };
    }
}
