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

namespace TakeoutSaaS.Application.App.Products.Handlers;

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

        IEnumerable<ProductCategory> filtered = categories;

        if (ProductCategoryManageMapping.TryParseStatus(request.Status, out var parsedStatus))
        {
            filtered = filtered.Where(item => item.IsEnabled == parsedStatus);
        }

        var normalizedKeyword = request.Keyword?.Trim().ToLowerInvariant();
        if (!string.IsNullOrWhiteSpace(normalizedKeyword))
        {
            filtered = filtered.Where(item =>
                item.Name.ToLower().Contains(normalizedKeyword) ||
                (item.Description != null && item.Description.ToLower().Contains(normalizedKeyword)));
        }

        var filteredList = filtered
            .OrderBy(item => item.SortOrder)
            .ThenBy(item => item.Id)
            .ToList();
        if (filteredList.Count == 0)
        {
            return [];
        }

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

        return filteredList
            .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();
    }
}
