namespace Netina.Core.EntityServices.OrderBagHandlers;

public class RemoveFromOrderBagCommandHandler(
    ICurrentUserService currentUserService,
    IRepositoryWrapper repositoryWrapper,
    IMediator mediator)
    : IRequestHandler<RemoveFromOrderBagCommand, OrderSDto>
{
    public async Task<OrderSDto> Handle(RemoveFromOrderBagCommand request, CancellationToken cancellationToken)
    {
        if (currentUserService.UserId == null)
            throw new AppException("Customer id notfound", ApiResultStatusCode.BadRequest);
        if (!Guid.TryParse(currentUserService.UserId, out Guid userId))
            throw new AppException("Customer id wrong", ApiResultStatusCode.BadRequest);

        var orderBag = await mediator.Send(new GetUserOrderBagQuery(), cancellationToken);

        foreach (var requestDto in request.RequestDtos)
        {
            var product = await repositoryWrapper.SetRepository<Product>()
                .TableNoTracking
                .FirstOrDefaultAsync(p => p.Id == requestDto.ProductId, cancellationToken);

            if (product == null)
                throw new AppException("Product not found ", ApiResultStatusCode.NotFound);
            if (!product.IsEnable)
                throw new AppException("Product is not enable", ApiResultStatusCode.BadRequest);


            orderBag.RemoveFromOrderBag(product.Id, requestDto.Count);
        }


        repositoryWrapper.SetRepository<Order>().Update(orderBag);
        await repositoryWrapper.SaveChangesAsync(cancellationToken);
        var order = await mediator.Send(new CalculateOrderCommand(orderBag.Id), cancellationToken);

        return order.AdaptToSDto();
    }
}