class StudentCafeteriaTransaction < Base::StudentCafeteriaTransaction
  belongs_to :school, foreign_key: :SchoolID
  belongs_to :family, foreign_key: :FamilyID
  belongs_to :student, foreign_key: :StudentID, optional: true
  belongs_to :family_deposit, foreign_key: :FDID, optional: true, dependent: :destroy

  has_one :lunch_order, foreign_key: :LTID, class_name: 'StudentLunchOrder', dependent: :destroy
  has_one :milk_order, foreign_key: :LTID, class_name: 'StudentMilkOrder', dependent: :destroy
  has_one :item_order, foreign_key: :LTID, class_name: 'StudentItemOrder', dependent: :destroy
  has_one :accounting_cafeteria_transaction, foreign_key: :cafeteria_transaction_id,
    class_name: 'Accounting::CafeteriaTransaction', dependent: :destroy
  has_one :accounting_transaction, through: :accounting_cafeteria_transaction

  scope :by_this_date_forward, ->(date) { where(date: date..Float::INFINITY) if date }

  def build_accounting_transaction(subcategory)
    family.accounting_transactions.build(
      amount: amount.abs,
      memo: memo,
      type: accounting_type,
      action: accounting_action,
      posted_on: date,
      student: student,
      subcategory: subcategory
    )
  end

  def process_payment(transaction)
    return unless payment?

    transaction.process_payment({
      payment: family_deposit.payment_method == 2 ? :check : :cash,
      check: { check_number: family_deposit.check_number }
    })
  end

  def payment?
    accounting_action == :payment
  end

  private
    def accounting_action
      return :charge if amount.negative?

      family_deposit_id.zero? ? :credit : :payment
    end

    def accounting_type
      amount.positive? ? 'Accounting::Decrease' : 'Accounting::Increase'
    end
end
