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

namespace TakeoutSaaS.Application.App.Orders.Handlers;

/// <summary>
/// 获取订单看板统计查询处理器。
/// </summary>
public sealed class GetOrderBoardStatsQueryHandler(IOrderRepository orderRepository)
    : IRequestHandler<GetOrderBoardStatsQuery, OrderBoardStatsDto>
{
    /// <inheritdoc />
    public async Task<OrderBoardStatsDto> Handle(GetOrderBoardStatsQuery request, CancellationToken cancellationToken)
    {
        // 1. 查询活跃订单
        var activeOrders = await orderRepository.GetActiveOrdersAsync(
            request.TenantId, request.StoreId, cancellationToken);

        // 2. 查询今日所有订单
        var todayStart = DateTime.UtcNow.Date;
        var todayOrders = await orderRepository.GetOrdersChangedSinceAsync(
            request.TenantId, request.StoreId, todayStart, cancellationToken);

        // 3. 统计各状态数量
        var allOrders = activeOrders.Concat(todayOrders).DistinctBy(o => o.Id).ToList();

        return new OrderBoardStatsDto
        {
            TodayTotal = allOrders.Count,
            PendingCount = allOrders.Count(o => o.Status == OrderStatus.AwaitingPreparation),
            MakingCount = allOrders.Count(o => o.Status == OrderStatus.InProgress),
            DeliveringCount = allOrders.Count(o => o.Status == OrderStatus.Ready),
            CompletedCount = allOrders.Count(o => o.Status == OrderStatus.Completed)
        };
    }
}
