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

namespace TakeoutSaaS.Application.App.Products.Handlers;

/// <summary>
/// 分类排序命令处理器。
/// </summary>
public sealed class SortProductCategoryCommandHandler(
    IProductRepository productRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<SortProductCategoryCommand, IReadOnlyList<ProductCategoryManageItemDto>>
{
    /// <inheritdoc />
    public async Task<IReadOnlyList<ProductCategoryManageItemDto>> Handle(SortProductCategoryCommand request, CancellationToken cancellationToken)
    {
        var tenantId = tenantProvider.GetCurrentTenantId();
        var categories = await productRepository.GetCategoriesByStoreAsync(tenantId, request.StoreId, false, cancellationToken);
        if (categories.Count == 0)
        {
            return [];
        }

        var sortMap = request.Items
            .Where(item => item.Sort > 0)
            .GroupBy(item => item.CategoryId)
            .ToDictionary(group => group.Key, group => group.Last().Sort);

        var sorted = categories
            .Select(category => new
            {
                Category = category,
                Sort = sortMap.GetValueOrDefault(category.Id, category.SortOrder)
            })
            .OrderBy(item => item.Sort)
            .ThenBy(item => item.Category.SortOrder)
            .ThenBy(item => item.Category.Id)
            .Select((item, index) =>
            {
                item.Category.SortOrder = index + 1;
                return item.Category;
            })
            .ToList();

        foreach (var category in sorted)
        {
            await productRepository.UpdateCategoryAsync(category, cancellationToken);
        }

        await productRepository.SaveChangesAsync(cancellationToken);

        var productCounts = await productRepository.CountProductsByCategoryIdsAsync(
            tenantId,
            request.StoreId,
            sorted.Select(item => item.Id).ToList(),
            cancellationToken);

        return sorted
            .Select(category => new ProductCategoryManageItemDto
            {
                Id = category.Id,
                Name = category.Name,
                Sort = category.SortOrder,
                ProductCount = productCounts.GetValueOrDefault(category.Id),
                Description = category.Description ?? string.Empty,
                Icon = category.Icon ?? string.Empty,
                Status = ProductCategoryManageMapping.ToStatusText(category.IsEnabled),
                Channels = ProductCategoryManageMapping.DeserializeChannels(category.ChannelsJson)
            })
            .ToList();
    }
}
