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

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

/// <summary>
/// 限时折扣选品分类查询处理器。
/// </summary>
public sealed class GetFlashSalePickerCategoriesQueryHandler(
    IProductRepository productRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<GetFlashSalePickerCategoriesQuery, IReadOnlyList<FlashSalePickerCategoryItemDto>>
{
    /// <inheritdoc />
    public async Task<IReadOnlyList<FlashSalePickerCategoryItemDto>> Handle(
        GetFlashSalePickerCategoriesQuery 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 FlashSalePickerCategoryItemDto
            {
                Id = item.Id,
                Name = item.Name,
                ProductCount = productCountLookup.GetValueOrDefault(item.Id, 0)
            })
            .ToList();
    }
}

