using MediatR;
using TakeoutSaaS.Application.App.Members.StoredCard.Dto;
using TakeoutSaaS.Application.App.Members.StoredCard.Queries;
using TakeoutSaaS.Domain.Membership.Repositories;
using TakeoutSaaS.Shared.Abstractions.Tenancy;

namespace TakeoutSaaS.Application.App.Members.StoredCard.Handlers;

/// <summary>
/// 储值卡充值记录列表查询处理器。
/// </summary>
public sealed class GetStoredCardRechargeRecordListQueryHandler(
    IStoredCardRepository repository,
    ITenantProvider tenantProvider)
    : IRequestHandler<GetStoredCardRechargeRecordListQuery, MemberStoredCardRechargeRecordListResultDto>
{
    /// <inheritdoc />
    public async Task<MemberStoredCardRechargeRecordListResultDto> Handle(
        GetStoredCardRechargeRecordListQuery request,
        CancellationToken cancellationToken)
    {
        var tenantId = tenantProvider.GetCurrentTenantId();
        var page = Math.Max(1, request.Page);
        var pageSize = Math.Clamp(request.PageSize, 1, 200);
        var normalizedKeyword = MemberStoredCardMapping.NormalizeKeyword(request.Keyword);
        var (startUtc, endUtc) = MemberStoredCardMapping.NormalizeDateRange(request.StartDateUtc, request.EndDateUtc);

        var (items, totalCount) = await repository.SearchRechargeRecordsAsync(
            tenantId,
            request.StoreId,
            startUtc,
            endUtc,
            normalizedKeyword,
            page,
            pageSize,
            cancellationToken);

        return new MemberStoredCardRechargeRecordListResultDto
        {
            Items = items.Select(MemberStoredCardDtoFactory.ToRechargeRecordDto).ToList(),
            Page = page,
            PageSize = pageSize,
            TotalCount = totalCount
        };
    }
}
