class Accounting::Category < ApplicationRecord
  audited

  has_associated_audits

  belongs_to :school

  has_many :subcategories, autosave: true, dependent: :restrict_with_error

  validates :name, presence: true, length: { maximum: 255 }

  before_create :build_non_viewable_subcategory

  before_destroy :destroy_non_viewable_subcategory, prepend: true

  def self.with_viewable
    joins(:subcategories).where('accounting_subcategories.viewable = true')
  end

  def self.order_with_subcategory
    includes(:subcategories).references(:subcategories)
      .order('accounting_categories.name, accounting_subcategories.name')
  end

  def self.ordered
    order(name: :asc)
  end

  private
    def build_non_viewable_subcategory
      subcategories.build(name: name, viewable: false)
    end

    def destroy_non_viewable_subcategory
      non_viewable = subcategories.find_by(viewable: false)
      return unless non_viewable && !non_viewable.child_associations?

      non_viewable.destroy!
    end
end
