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

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

/// <summary>
/// 秒杀选品分类查询处理器。
/// </summary>
public sealed class GetSeckillPickerCategoriesQueryHandler(
    IProductRepository productRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<GetSeckillPickerCategoriesQuery, IReadOnlyList<SeckillPickerCategoryItemDto>>
{
    /// <inheritdoc />
    public async Task<IReadOnlyList<SeckillPickerCategoryItemDto>> Handle(
        GetSeckillPickerCategoriesQuery request,
        CancellationToken cancellationToken)
    {
        var tenantId = tenantProvider.GetCurrentTenantId();
        var categories = await productRepository.GetCategoriesByStoreAsync(
            tenantId,
            request.OperationStoreId,
            true,
            cancellationToken);
        if (categories.Count == 0)
        {
            return [];
        }

        var categoryIds = categories.Select(item => item.Id).ToList();
        var productCountLookup = await productRepository.CountProductsByCategoryIdsAsync(
            tenantId,
            request.OperationStoreId,
            categoryIds,
            cancellationToken);

        return categories
            .Select(item => new SeckillPickerCategoryItemDto
            {
                Id = item.Id,
                Name = item.Name,
                ProductCount = productCountLookup.GetValueOrDefault(item.Id, 0)
            })
            .ToList();
    }
}


