require 'rails_helper'

RSpec.describe 'Admin/global settings', type: :feature do
  let(:user) { create :user }

  before do
    allow(Devise::LDAP::Adapter).to receive(:get_ldap_param)
      .with(user.cn, :admin).and_return(["true"])

    login_as user, :scope => :user
  end

  scenario 'Update reserved usernames' do
    visit admin_settings_registrations_path
    expect(Setting.reserved_usernames).not_to include(['Kosmos', 'Kredits'])

    fill_in 'Reserved usernames', with: "Kosmos\nKredits"
    click_button "Save"
    expect(Setting.reserved_usernames).to eq(['Kosmos', 'Kredits'])
  end

  describe "Service settings" do
    scenario "Opening service settings shows page for first service" do
      visit admin_settings_services_path

      expect(current_url).to eq(admin_settings_services_url(params: { s: "btcpay" }))
    end

    scenario "View service settings" do
      visit admin_settings_services_path(params: { s: "ejabberd" })

      expect(page).to have_content("Enable ejabberd integration")
      expect(page).to have_field("API URL", with: "http://xmpp.example.com/api")
    end

    scenario "Disable a service integration" do
      visit admin_settings_services_path(params: { s: "ejabberd" })
      expect(page).to have_checked_field("setting[ejabberd_enabled]")

      uncheck "setting[ejabberd_enabled]"
      click_button "Save"

      expect(current_url).to eq(admin_settings_services_url(params: { s: "ejabberd" }))
      expect(page).to_not have_checked_field("setting[ejabberd_enabled]")
      expect(page).to_not have_field("API URL", disabled: true)
    end

    scenario "Resettable fields" do
      visit admin_settings_services_path(params: { s: "ejabberd" })
      expect(page).to have_field("API URL", with: "http://xmpp.example.com/api")
      expect(page).to_not have_css('input#setting_ejabberd_api_url+button')

      Setting.ejabberd_api_url = "http://example.com/foo"
      visit admin_settings_services_path(params: { s: "ejabberd" })
      expect(page).to have_field("API URL", with: "http://example.com/foo")
      expect(page).to have_css('input#setting_ejabberd_api_url+button')
    end
  end
end
