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

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

/// <summary>
/// 查询积分商城兑换记录分页处理器。
/// </summary>
public sealed class GetPointMallRecordListQueryHandler(
    IPointMallRepository repository,
    ITenantProvider tenantProvider)
    : IRequestHandler<GetPointMallRecordListQuery, MemberPointMallRecordListResultDto>
{
    /// <inheritdoc />
    public async Task<MemberPointMallRecordListResultDto> Handle(
        GetPointMallRecordListQuery request,
        CancellationToken cancellationToken)
    {
        var tenantId = tenantProvider.GetCurrentTenantId();
        var redeemType = MemberPointMallMapping.TryParseRedeemType(request.RedeemType);
        var status = MemberPointMallMapping.TryParseRecordStatus(request.Status);
        var keyword = MemberPointMallMapping.NormalizeKeyword(request.Keyword);
        var page = Math.Max(1, request.Page);
        var pageSize = Math.Clamp(request.PageSize, 1, 200);
        var (startUtc, endUtc) = MemberPointMallMapping.NormalizeDateRange(
            request.StartDateUtc,
            request.EndDateUtc);

        var (items, totalCount) = await repository.SearchRecordsAsync(
            tenantId,
            request.StoreId,
            redeemType,
            status,
            startUtc,
            endUtc,
            keyword,
            page,
            pageSize,
            cancellationToken);

        var stats = await repository.GetRecordStatsAsync(
            tenantId,
            request.StoreId,
            DateTime.UtcNow,
            cancellationToken);

        return new MemberPointMallRecordListResultDto
        {
            Items = items.Select(MemberPointMallDtoFactory.ToRecordDto).ToList(),
            Page = page,
            PageSize = pageSize,
            TotalCount = totalCount,
            Stats = MemberPointMallDtoFactory.ToRecordStatsDto(stats)
        };
    }
}
