using Netina.Domain.Entities.Orders;

namespace Netina.Repository.Handlers.Orders;

public class GetOrderQueryHandler(IRepositoryWrapper repositoryWrapper) : IRequestHandler<GetOrderQuery, Order>
{
    public async Task<Order> Handle(GetOrderQuery request, CancellationToken cancellationToken)
    {
        var order = await repositoryWrapper.SetRepository<Order>()
            .TableNoTracking
            .FirstOrDefaultAsync(o => o.Id == request.Id, cancellationToken);

        if (order == null)
            throw new AppException("Order not found", ApiResultStatusCode.NotFound);

        var orderProducts = await repositoryWrapper.SetRepository<OrderProduct>()
            .TableNoTracking
            .Where(op => op.OrderId == order.Id)
            .ToListAsync(cancellationToken);

        orderProducts.ForEach(op => order.AddOrderProduct(op));

        var orderDelivery= await repositoryWrapper.SetRepository<OrderDelivery>()
            .TableNoTracking
            .FirstOrDefaultAsync(od => od.OrderId == request.Id, cancellationToken);
        if (orderDelivery != null)
        {
            order.AddOrderDelivery(orderDelivery.AddressId, orderDelivery.DeliveryCost, orderDelivery.ShippingId, orderDelivery.OrderId, orderDelivery.Id);
        }

        return order;
    }
}