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

namespace TakeoutSaaS.Application.App.Members.Handlers;

/// <summary>
/// 会员列表查询处理器。
/// </summary>
public sealed class SearchMemberListQueryHandler(
    IMemberRepository memberRepository,
    IOrderRepository orderRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<SearchMemberListQuery, PagedResult<MemberListItemDto>>
{
    /// <inheritdoc />
    public async Task<PagedResult<MemberListItemDto>> Handle(
        SearchMemberListQuery request,
        CancellationToken cancellationToken)
    {
        var page = Math.Max(1, request.Page);
        var pageSize = Math.Clamp(request.PageSize, 1, 200);

        if (request.VisibleStoreIds.Count == 0)
        {
            return new PagedResult<MemberListItemDto>([], page, pageSize, 0);
        }

        var context = await MemberCenterSupport.LoadMemberContextAsync(
            memberRepository,
            orderRepository,
            tenantProvider,
            request.VisibleStoreIds,
            cancellationToken);

        var filtered = MemberCenterSupport.ApplyFilters(
            context.Aggregates,
            request.Keyword,
            request.TierId)
            .OrderByDescending(item => item.Metrics.LastOrderAt)
            .ThenByDescending(item => item.MemberId)
            .ToList();

        var totalCount = filtered.Count;
        var items = filtered
            .Skip((page - 1) * pageSize)
            .Take(pageSize)
            .Select(item => new MemberListItemDto
            {
                MemberId = item.MemberId,
                Name = item.Name,
                AvatarText = item.AvatarText,
                AvatarColor = item.AvatarColor,
                MobileMasked = item.MobileMasked,
                TierId = item.Tier?.Id,
                TierName = item.Tier?.Name ?? string.Empty,
                TierColorHex = item.Tier?.ColorHex ?? "#999999",
                TotalAmount = decimal.Round(item.Metrics.TotalAmount, 2, MidpointRounding.AwayFromZero),
                OrderCount = item.Metrics.TotalOrderCount,
                LastOrderAt = item.Metrics.LastOrderAt,
                StoredBalance = item.Profile.StoredBalance,
                PointsBalance = Math.Max(0, item.Profile.PointsBalance),
                IsDormant = item.IsDormant
            })
            .ToList();

        return new PagedResult<MemberListItemDto>(items, page, pageSize, totalCount);
    }
}
