class Family::Accounting::LegacyBalancesController < Family::Controller
  include AccountingHelper

  def index
    accounts = family_accounts.merge(childcare: :Childcare, cafeteria: :Cafeteria)
    render_success :ok, json: accounts.map { |k, n| props(k, n) }.compact
  end

  private
    def family_transactions
      @family_transactions ||= current_family.family_transactions.group_by(&:account_id)
    end

    def all_transactions
      @all_transactions ||= family_transactions
        .merge(childcare: current_family.daycare_transactions)
        .merge(cafeteria: current_family.student_cafeteria_transactions)
    end

    def family_accounts
      current_school.family_accounts
        .by_active
        .by_family_viewable
        .where(id: family_transactions.keys)
        .ordered
        .pluck(:id, :name)
        .to_h
    end

    def props(key, name)
      balance = all_transactions[key].map(&:amount).reduce(0, :+)
      return if balance.zero?

      {
        name: name,
        balance: sprintf('%.2f', balance)
      }
    end
end
