using NetinaShop.Domain.Entities.Warehouses;

namespace NetinaShop.Core.EntityServices.OrderBagHandlers;

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

    public SubmitOrderDeliveryCommandHandler(IMediator mediator, IRepositoryWrapper repositoryWrapper)
    {
        _mediator = mediator;
        _repositoryWrapper = repositoryWrapper;
    }
    public async Task<bool> Handle(SubmitOrderDeliveryCommand request, CancellationToken cancellationToken)
    {
        var order = await _mediator.Send(new GetOrderQuery(request.OrderId), cancellationToken);
        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);
        foreach (var orderDelivery in order.OrderDeliveries)
        {
            _repositoryWrapper.SetRepository<OrderDelivery>()
                .Delete(orderDelivery);
            await _repositoryWrapper.SaveChangesAsync(cancellationToken);
        }
        order.OrderDeliveries.Clear();
        order.AddOrderDelivery(request.Address,request.PostalCode,request.ReceiverPhoneNumber,request.ReceiverFullName,shipping.DeliveryCost,request.ShippingId,request.OrderId);

        _repositoryWrapper.SetRepository<Order>().Update(order);
        await _repositoryWrapper.SaveChangesAsync(cancellationToken);
        await _mediator.Send(new CalculateOrderCommand(order.Id), cancellationToken);
        return true;
    }
}