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

namespace TakeoutSaaS.Application.App.Products.Handlers;

/// <summary>
/// 分类列表查询处理器。
/// </summary>
public sealed class GetProductCategoryListQueryHandler(
    IProductRepository productRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<GetProductCategoryListQuery, IReadOnlyList<ProductCategoryListItemDto>>
{
    /// <inheritdoc />
    public async Task<IReadOnlyList<ProductCategoryListItemDto>> Handle(GetProductCategoryListQuery request, CancellationToken cancellationToken)
    {
        var tenantId = tenantProvider.GetCurrentTenantId();
        var categories = await productRepository.GetCategoriesByStoreAsync(tenantId, request.StoreId, false, cancellationToken);
        if (categories.Count == 0)
        {
            return [];
        }

        var categoryIds = categories.Select(x => x.Id).ToList();
        var productCounts = await productRepository.CountProductsByCategoryIdsAsync(tenantId, request.StoreId, categoryIds, cancellationToken);
        return categories
            .OrderBy(x => x.SortOrder)
            .ThenBy(x => x.Id)
            .Select(category => new ProductCategoryListItemDto
            {
                Id = category.Id,
                Name = category.Name,
                Sort = category.SortOrder,
                ProductCount = productCounts.GetValueOrDefault(category.Id)
            })
            .ToList();
    }
}
