using Microsoft.EntityFrameworkCore;
using Netina.Domain.Entities.Orders;

namespace Netina.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 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;
    }
}