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 GetProductAddonGroupListQueryHandler(
    IProductRepository productRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<GetProductAddonGroupListQuery, IReadOnlyList<ProductAddonTemplateItemDto>>
{
    /// <inheritdoc />
    public async Task<IReadOnlyList<ProductAddonTemplateItemDto>> Handle(GetProductAddonGroupListQuery request, CancellationToken cancellationToken)
    {
        // 1. 读取门店下的加料模板。
        var tenantId = tenantProvider.GetCurrentTenantId();
        var templates = await productRepository.GetAddonTemplatesByStoreAsync(tenantId, request.StoreId, cancellationToken);
        if (templates.Count == 0)
        {
            return [];
        }

        // 2. 按状态与关键字过滤。
        IEnumerable<ProductSpecTemplate> filtered = templates;
        if (!string.IsNullOrWhiteSpace(request.Status))
        {
            if (!ProductAddonTemplateMapping.TryParseStatus(request.Status, out var isEnabled))
            {
                return [];
            }

            filtered = filtered.Where(item => item.IsEnabled == isEnabled);
        }

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

        // 3. 批量读取选项与关联商品。
        var filteredList = filtered
            .OrderBy(item => item.SortOrder)
            .ThenBy(item => item.Id)
            .ToList();
        if (filteredList.Count == 0)
        {
            return [];
        }

        var templateIds = filteredList.Select(item => item.Id).ToList();
        var options = await productRepository.GetSpecTemplateOptionsByTemplateIdsAsync(templateIds, tenantId, cancellationToken);
        var relations = await productRepository.GetSpecTemplateProductsByTemplateIdsAsync(templateIds, tenantId, request.StoreId, cancellationToken);

        // 4. 构建字典并映射 DTO。
        var optionsLookup = options
            .GroupBy(x => x.TemplateId)
            .ToDictionary(group => group.Key, group => group.OrderBy(item => item.SortOrder).ThenBy(item => item.Id).ToList());
        var productIdsLookup = relations
            .GroupBy(x => x.TemplateId)
            .ToDictionary(group => group.Key, group => group.Select(item => item.ProductId).ToList());

        return filteredList
            .Select(template => ProductAddonTemplateDtoFactory.ToDto(template, optionsLookup, productIdsLookup))
            .ToList();
    }
}
