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.Tenancy;

namespace TakeoutSaaS.Application.App.Members.Handlers;

/// <summary>
/// 会员列表统计查询处理器。
/// </summary>
public sealed class GetMemberListStatsQueryHandler(
    IMemberRepository memberRepository,
    IOrderRepository orderRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<GetMemberListStatsQuery, MemberListStatsDto>
{
    /// <inheritdoc />
    public async Task<MemberListStatsDto> Handle(
        GetMemberListStatsQuery request,
        CancellationToken cancellationToken)
    {
        if (request.VisibleStoreIds.Count == 0)
        {
            return new MemberListStatsDto();
        }

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

        var filtered = MemberCenterSupport.ApplyFilters(
            context.Aggregates,
            request.Keyword,
            request.TierId);

        var nowUtc = DateTime.UtcNow;
        var monthStart = new DateTime(nowUtc.Year, nowUtc.Month, 1, 0, 0, 0, DateTimeKind.Utc);

        return new MemberListStatsDto
        {
            TotalMembers = filtered.Count,
            MonthlyNewMembers = filtered.Count(item => item.JoinedAt >= monthStart),
            ActiveMembers = filtered.Count(item => item.Metrics.LastOrderAt >= nowUtc.AddDays(-30)),
            DormantMembers = filtered.Count(item => item.Metrics.LastOrderAt < nowUtc.AddDays(-60))
        };
    }
}
