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 GetProductScheduleListQueryHandler(
    IProductRepository productRepository,
    ITenantProvider tenantProvider)
    : IRequestHandler<GetProductScheduleListQuery, IReadOnlyList<ProductScheduleItemDto>>
{
    /// <inheritdoc />
    public async Task<IReadOnlyList<ProductScheduleItemDto>> Handle(GetProductScheduleListQuery request, CancellationToken cancellationToken)
    {
        // 1. 读取门店时段规则。
        var tenantId = tenantProvider.GetCurrentTenantId();
        var schedules = await productRepository.GetSchedulesByStoreAsync(tenantId, request.StoreId, cancellationToken);
        if (schedules.Count == 0)
        {
            return [];
        }

        // 2. 按状态与关键字过滤。
        IEnumerable<ProductSchedule> filtered = schedules;
        if (!string.IsNullOrWhiteSpace(request.Status))
        {
            if (!ProductScheduleMapping.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));
        }

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

        // 3. 批量读取关联商品并映射 DTO。
        var scheduleIds = filteredList.Select(item => item.Id).ToList();
        var relations = await productRepository.GetScheduleProductsByScheduleIdsAsync(
            scheduleIds,
            tenantId,
            request.StoreId,
            cancellationToken);
        var productIdsLookup = relations
            .GroupBy(x => x.ScheduleId)
            .ToDictionary(group => group.Key, group => group.Select(item => item.ProductId).ToList());

        return filteredList
            .Select(schedule => ProductScheduleDtoFactory.ToDto(schedule, productIdsLookup))
            .ToList();
    }
}
