using MediatR;
using TakeoutSaaS.Application.App.Orders.Dto;
using TakeoutSaaS.Application.App.Orders.Queries;
using TakeoutSaaS.Domain.Orders.Entities;
using TakeoutSaaS.Domain.Orders.Repositories;

namespace TakeoutSaaS.Application.App.Orders.Handlers;

/// <summary>
/// 获取指定时间后的待处理订单查询处理器。
/// </summary>
public sealed class GetPendingOrdersSinceQueryHandler(IOrderRepository orderRepository)
    : IRequestHandler<GetPendingOrdersSinceQuery, IReadOnlyList<OrderBoardCardDto>>
{
    /// <inheritdoc />
    public async Task<IReadOnlyList<OrderBoardCardDto>> Handle(
        GetPendingOrdersSinceQuery request, CancellationToken cancellationToken)
    {
        // 1. 查询指定时间后变更的订单
        var orders = await orderRepository.GetOrdersChangedSinceAsync(
            request.TenantId, request.StoreId, request.Since, cancellationToken);

        // 2. 获取商品摘要
        var orderIds = orders.Select(o => o.Id).ToList();
        var itemsMap = orderIds.Count > 0
            ? await orderRepository.GetItemsByOrderIdsAsync(orderIds, request.TenantId, cancellationToken)
            : new Dictionary<long, IReadOnlyList<OrderItem>>();

        // 3. 映射为卡片 DTO
        return orders.Select(o =>
        {
            var items = itemsMap.TryGetValue(o.Id, out var list) ? list : [];
            var summary = items.Count > 0
                ? string.Join("、", items.Take(3).Select(x => x.ProductName))
                  + (items.Count > 3 ? $" 等{items.Count}件" : string.Empty)
                : string.Empty;

            return new OrderBoardCardDto
            {
                Id = o.Id,
                OrderNo = o.OrderNo,
                StoreId = o.StoreId,
                Channel = o.Channel,
                DeliveryType = o.DeliveryType,
                Status = o.Status,
                CustomerName = o.CustomerName,
                CustomerPhone = o.CustomerPhone,
                TableNo = o.TableNo,
                QueueNumber = o.QueueNumber,
                ItemsSummary = summary,
                PaidAmount = o.PaidAmount,
                CreatedAt = o.CreatedAt
            };
        }).ToList();
    }
}
