class Expense < ActiveRecord::Base
  belongs_to :expensesconcept
  belongs_to :open_cash_register
  has_many :cash_registers_moves

  ##--- Llevar registro de Actividad del usuario
  audited

  enum status: [:canceled, :active, :registered]

  attr_accessor :skip_open_cash_validation
  attr_accessor :skip_open_cash_has_money

  validates_presence_of :quantity, message: "Se debe indicar la cantidad."
  validates_numericality_of :quantity, greater_than: 0.00, message: "La cantidad debe ser mayor a $0"
  validates_presence_of :open_cash_register_id, message: "Se debe elegir caja registradora.", unless: :skip_open_cash_validation
  validates_presence_of :expensesconcept_id, message: "Se debe elegir concepto de egreso."

  validate :open_cash_has_money?, unless: :skip_open_cash_has_money, on: :create

  scope :activos, -> { where(status: 2).order("created_at") }

  def open_cash_has_money?
    money_in_cash = 0
    money_in_cash += open_cash_register.initial_cash

    CashRegistersMove.where(open_cash_register_id: open_cash_register.id, move_type: '0').each do |move|
      money_in_cash -= move.quantity
    end

    CashRegistersMove.where(open_cash_register_id: open_cash_register.id, move_type: '1').each do |move|
      money_in_cash += move.quantity
    end

    if money_in_cash >= quantity
      return true
    else
      errors.add :quantity, "La cantidad es superior al efectivo disponible en caja."
    end
  end
end
