class ItemInCart < ActiveRecord::Base
  belongs_to :cart
  belongs_to :item

  validates_uniqueness_of :item_id, scope: :cart_id
  validates :item_id, presence: true
  validates :cart_id, presence: true

  def self.update_state(cart_id, item_id, count)
    item_in_cart = nil
    ItemInCart.transaction do
      item_in_cart = ItemInCart.where(cart_id: cart_id, item_id: item_id).first
      item_in_cart ||= ItemInCart.new(cart_id: cart_id, item_id: item_id)
      item_in_cart.count = count
      item_in_cart.price = item_in_cart.item.list_price
      item_in_cart.commission = (((item_in_cart.item.list_price - item_in_cart.item.current_input_price) / (item_in_cart.item.current_input_price)) * 100).round(2)
      item_in_cart.save!
      item_in_cart.destroy! if count <= 0
    end
    return item_in_cart
  end
end
