class Billing::TransactionDetail < ApplicationRecord
  attr_accessor :transaction_days

  belongs_to :subcategory, class_name: 'Accounting::Subcategory'

  has_many :plan_transactions, foreign_key: :detail_id, dependent: :destroy
  has_many :days, class_name: 'Billing::TransactionDay',
    foreign_key: :detail_id, dependent: :destroy
  has_many :processed_transactions, through: :plan_transactions

  has_one :template_transaction, foreign_key: :detail_id, dependent: :destroy

  delegate :template, to: :template_transactions, allow_nil: true

  before_save :set_transaction_days

  scope :by_plan_school_year, ->(school_year) { merge(Billing::Plan.by_school_year(school_year)) }

  def type?
    template_transaction.nil? ? :student : :template
  end

  private
    def set_transaction_days
      return if transaction_days.blank?

      transaction_days.each { |d| days.build(date: d) }
    end
end
