using MediatR;
using TakeoutSaaS.Application.App.Coupons.NewCustomer.Dto;
using TakeoutSaaS.Application.App.Coupons.NewCustomer.Queries;
using TakeoutSaaS.Domain.Coupons.Repositories;
using TakeoutSaaS.Shared.Abstractions.Tenancy;

namespace TakeoutSaaS.Application.App.Coupons.NewCustomer.Handlers;

/// <summary>
/// 查询新客邀请记录分页处理器。
/// </summary>
public sealed class GetNewCustomerInviteRecordListQueryHandler(
    INewCustomerGiftRepository repository,
    ITenantProvider tenantProvider)
    : IRequestHandler<GetNewCustomerInviteRecordListQuery, NewCustomerInviteRecordListResultDto>
{
    /// <inheritdoc />
    public async Task<NewCustomerInviteRecordListResultDto> Handle(
        GetNewCustomerInviteRecordListQuery request,
        CancellationToken cancellationToken)
    {
        var tenantId = tenantProvider.GetCurrentTenantId();
        var normalizedPage = Math.Max(1, request.Page);
        var normalizedPageSize = Math.Clamp(request.PageSize, 1, 200);

        var (items, totalCount) = await repository.GetInviteRecordsAsync(
            tenantId,
            request.StoreId,
            normalizedPage,
            normalizedPageSize,
            cancellationToken);

        return new NewCustomerInviteRecordListResultDto
        {
            Items = items.Select(NewCustomerMapping.ToInviteRecordDto).ToList(),
            Page = normalizedPage,
            PageSize = normalizedPageSize,
            TotalCount = totalCount
        };
    }
}
