class Billing::Plan < ApplicationRecord
  attr_accessor :details

  belongs_to :student
  belongs_to :school_year

  has_many :plan_transactions, dependent: :destroy
  has_many :transaction_details, through: :plan_transactions, source: :detail
  has_many :processed_transactions, through: :plan_transaction, dependent: :destroy

  before_save :remove_processed_transactions, if: :details
  before_save :attach_details, if: :details

  scope :by_school_year, ->(school_year) { where(school_year_id: school_year) if school_year }
  scope :by_student, ->(id) { where(student: id) if id.present? }

  private
    def attach_details
      self.transaction_details = details
    end

    def remove_processed_transactions
      removed_details = transaction_details - details
      removed_details.each do |remove_detail|
        remove_detail.processed_transactions.by_plan(id).each(&:destroy)
      end
    end
end
