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 GetStoredCardPlanListQueryHandler(
    IStoredCardRepository repository,
    ITenantProvider tenantProvider)
    : IRequestHandler<GetStoredCardPlanListQuery, MemberStoredCardPlanListResultDto>
{
    /// <inheritdoc />
    public async Task<MemberStoredCardPlanListResultDto> Handle(
        GetStoredCardPlanListQuery request,
        CancellationToken cancellationToken)
    {
        var tenantId = tenantProvider.GetCurrentTenantId();

        var plans = await repository.GetPlansByStoreAsync(
            tenantId,
            request.StoreId,
            cancellationToken);

        var planIds = plans.Select(item => item.Id).ToList();
        var aggregates = await repository.GetPlanAggregatesAsync(
            tenantId,
            request.StoreId,
            planIds,
            cancellationToken);

        var items = plans
            .Select(item =>
            {
                var aggregate = aggregates.TryGetValue(item.Id, out var value)
                    ? value
                    : MemberStoredCardDtoFactory.EmptyAggregate(item.Id);

                return MemberStoredCardDtoFactory.ToPlanDto(item, aggregate);
            })
            .ToList();

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

        return new MemberStoredCardPlanListResultDto
        {
            Items = items,
            Stats = MemberStoredCardDtoFactory.ToPlanStatsDto(stats)
        };
    }
}
