class Admin::Accounting::Invoices::ChargesController < Admin::Accounting::Controller
  def index
    render_success :ok, json: charges.decorate.map { |c| charges_props(c) }
  end

  private
    def charges
      invoice.charges.includes(
        :transaction_details,
        :increase_allocations,
        :students,
        { subcategories: :category }
      )
    end

    def invoice
      @invoice ||= current_school.accounting_invoices.find_by(id: params[:invoice_id])
    end

    def allocations_by_increase
      @allocations_by_increase ||= invoice.allocations
        .includes(decrease: :accounting_transaction)
        .group_by(&:increase_id)
    end

    def decrease_props(allocation)
      {
        posted_on: allocation.decrease.accounting_transaction.posted_on,
        type: allocation.decrease.accounting_transaction.action,
        memo: allocation.decrease.accounting_transaction.memo,
        amount: allocation.amount
      }
    end

    def charges_props(charge)
      detail_id = charge.transaction_details.first.id
      {
        transaction_id: charge.id,
        posted_on: charge.posted_on,
        student: charge.students.first.full_name(:reverse),
        category: charge.category_name,
        charged: charge.amount,
        paid: charge.allocated,
        due: charge.balance,
        allocations: allocations_by_increase[detail_id]&.map { |i| decrease_props(i) } || []
      }
    end
end
