class Billing::TemplateTransaction < ApplicationRecord
  belongs_to :template
  belongs_to :detail, class_name: 'Billing::TransactionDetail', foreign_key: :detail_id,
    dependent: :destroy

  has_many :plan_transactions, through: :detail

  delegate :school, to: :template

  after_create :attach_new_transactions

  scope :with_template, ->(template) { where(template_id: template) if template }

  private
    def attach_new_transactions
      plan_ids = template.plan_transactions.pluck(:plan_id).uniq
      plans = school.billing_plans.where(id: plan_ids)
      plans.each { |p| p.transaction_details << detail }
    end
end
