class Admin::Accounting::CreditsController < Admin::Accounting::Controller
  def create
    credits = []
    students.each do |student|
      credit = student.family.accounting_decreases.build(credit_params(student))
      credits += student.accounting_transaction_matrix(credit)
    end
    credits << validate_credits if credits.blank?
    if transactional_save(credits)
      allocate_funds
      message = credits.many? ? 'Credits' : 'Credit'
      render_success :ok, object: message
    else
      render_error :unprocessable_entity, errors: credits.first
    end
  end

  private
    def students
      @students ||= current_school.students.where(id: params[:students])
    end

    def subcategory
      @subcategory ||= current_school.accounting_subcategories.find_by(id: params[:subcategory_id])
    end

    def credit_params(student=nil)
      params.require(:credit).permit(:amount, :memo, :posted_on).merge(
        action: :credit,
        student: student,
        subcategory: subcategory,
        tag_ids: params[:credit][:tag_ids]
      )
    end

    def validate_credits
      Accounting::Decrease.new(credit_params)
    end

    def allocate_funds
      students.each do |student|
        AllocationJob.perform_now(
          student.family,
          subcategory,
          student: student,
          audit_user: current_user
        )
        next unless student.family_two

        AllocationJob.perform_now(
          student.family_two,
          @subcategory,
          audit_user: current_user
        )
      end
    end
end
