using NetinaShop.Domain.Entities.Orders;

namespace NetinaShop.Repository.Handlers.Orders;

public class GetOrderQueryHandler : IRequestHandler<GetOrderQuery, Order>
{
    private readonly IRepositoryWrapper _repositoryWrapper;

    public GetOrderQueryHandler(IRepositoryWrapper repositoryWrapper)
    {
        _repositoryWrapper = repositoryWrapper;
    }
    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 orderDeliveries = await _repositoryWrapper.SetRepository<OrderDelivery>()
            .TableNoTracking
            .Where(od => od.OrderId == request.Id)
            .ToListAsync(cancellationToken);

        orderDeliveries.ForEach(od=>order.AddOrderDelivery(od.Address,od.PostalCode,od.ReceiverPhoneNumber,od.ReceiverFullName,od.DeliveryCost,od.ShippingId,od.OrderId));

        return order;
    }
}