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

        // 2. 应用状态、类型、关键字筛选。
        IEnumerable<ProductSpecTemplate> filtered = templates;
        if (ProductSpecTemplateMapping.TryParseStatus(request.Status, out var parsedStatus))
        {
            filtered = filtered.Where(item => item.IsEnabled == parsedStatus);
        }

        if (ProductSpecTemplateMapping.TryParseTemplateType(request.Type, out var templateType))
        {
            filtered = filtered.Where(item => item.TemplateType == templateType);
        }

        var normalizedKeyword = request.Keyword?.Trim().ToLowerInvariant();
        if (!string.IsNullOrWhiteSpace(normalizedKeyword))
        {
            filtered = filtered.Where(item => item.Name.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 => ProductSpecTemplateDtoFactory.ToDto(template, optionsLookup, productIdsLookup))
            .ToList();
    }
}
