using NetinaShop.Domain.Entities.Orders;
using NetinaShop.Domain.Entities.Warehouses;

namespace NetinaShop.Core.EntityServices.OrderBagHandlers;

public class SubmitOrderDeliveryCommandHandler : IRequestHandler<SubmitOrderDeliveryCommand, OrderSDto>
{
    private readonly IMediator _mediator;
    private readonly IRepositoryWrapper _repositoryWrapper;

    public SubmitOrderDeliveryCommandHandler(IMediator mediator, IRepositoryWrapper repositoryWrapper)
    {
        _mediator = mediator;
        _repositoryWrapper = repositoryWrapper;
    }
    public async Task<OrderSDto> Handle(SubmitOrderDeliveryCommand request, CancellationToken cancellationToken)
    {
        var order = await _repositoryWrapper.SetRepository<Order>()
            .TableNoTracking
            .FirstOrDefaultAsync(o => o.Id == request.OrderId, cancellationToken);

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

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

        var shipping = await _repositoryWrapper.SetRepository<Shipping>()
            .TableNoTracking
            .FirstOrDefaultAsync(s => s.Id == request.ShippingId, cancellationToken);
        if (shipping == null)
            throw new AppException("Shipping not found", ApiResultStatusCode.NotFound);

        order.AddOrderDelivery(request.AddressId, shipping.DeliveryCost, request.ShippingId, request.OrderId);

        _repositoryWrapper.SetRepository<Order>().Update(order);
        await _repositoryWrapper.SaveChangesAsync(cancellationToken);

        var calculatedOrder = await _mediator.Send(new CalculateOrderCommand(order.Id), cancellationToken);
        return calculatedOrder.AdaptToSDto();
    }
}