class Accounting::Allocation < ApplicationRecord
  belongs_to :increase, class_name: 'Accounting::TransactionDetail'
  belongs_to :decrease, class_name: 'Accounting::TransactionDetail'

  validates :amount, numericality: { greater_than: 0 }

  validate :actions_match
  validate :students_match

  before_destroy :open_associated_transactions

  private
    def actions_match
      increase_transaction = increase.accounting_transaction
      decrease_transaction = decrease.accounting_transaction
      # these work with everything
      return if increase_transaction.charge?
      return if decrease_transaction.payment?

      # only three options left to check on each side
      return if increase_transaction.refund? && decrease_transaction.transfer?
      return if increase_transaction.transfer? && !decrease_transaction.void?
      return if increase_transaction.void? && decrease_transaction.transfer?

      errors.add(:base, 'Increase action must match decrease action')
    end

    def categories_match
      return if increase.category == decrease.category
      return if decrease.category.nil?

      errors.add(:base, 'Increase category must match decrease category')
    end

    def students_match
      return if increase.student == decrease.student
      return if decrease.student.nil?

      errors.add(:base, 'Increase student must match decrease student')
    end

    def open_associated_transactions
      increase.update_attribute(:closed, false)
      decrease.update_attribute(:closed, false)
    end
end
