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

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

/// <summary>
/// 到账汇总分页查询处理器。
/// </summary>
public sealed class SearchFinanceSettlementListQueryHandler(
    IFinanceTransactionRepository financeTransactionRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<SearchFinanceSettlementListQuery, FinanceSettlementListResultDto>
{
    /// <inheritdoc />
    public async Task<FinanceSettlementListResultDto> Handle(
        SearchFinanceSettlementListQuery request,
        CancellationToken cancellationToken)
    {
        var tenantId = tenantProvider.GetCurrentTenantId();
        var normalizedPage = Math.Max(1, request.Page);
        var normalizedPageSize = Math.Clamp(request.PageSize, 1, 200);

        var snapshot = await financeTransactionRepository.SearchSettlementPageAsync(
            tenantId,
            request.StoreId,
            request.StartAt,
            request.EndAt,
            request.PaymentMethod,
            normalizedPage,
            normalizedPageSize,
            cancellationToken);

        return new FinanceSettlementListResultDto
        {
            Items = snapshot.Items.Select(FinanceSettlementMapping.ToListItem).ToList(),
            Total = snapshot.TotalCount,
            Page = normalizedPage,
            PageSize = normalizedPageSize
        };
    }
}
