class Admin::Payjunction::CredentialsController < Admin::Controller
  def show
    render_success :ok, json: credential
  end

  def update
    if credential
      if credential.update(credential_params)
        render_success :ok
      else
        render_error :unprocessable_entity, errors: credential
      end
    else
      credential = current_school.build_payjunction_credential(credential_params)
      if credential.save
        render_success :ok, message: 'PayJuntion Credentials created.'
      else
        render_error :unprocessable_entity, errors: credential
      end
    end
  end

  def destroy
    objects = terminals + accounts + [credential]
    if transactional_destroy(objects)
      render_success :ok, message: 'PayJunction settings removed.'
    else
      render_error :unprocessable_entity, message: 'Something went wrong.'
    end
  end

  private
    def credential
      @credential ||= current_school.payjunction_credential
    end

    def credential_params
      params.permit(:username, :password)
    end

    def accounts
      current_school.payjunction_accounts
    end

    def terminals
      current_school.payjunction_terminals
    end
end
