require "rails_helper"

RSpec.describe "Admin: User management", type: :feature do
  let(:admin) { create :user }
  let(:user) { create :user, id: 2, cn: "alfred", email: "alfred@example.com" }

  before do
    user.save!

    allow(Devise::LDAP::Adapter).to receive(:get_ldap_param)
      .with(admin.cn, :admin).and_return(["true"])
    allow(Devise::LDAP::Adapter).to receive(:get_ldap_param)
      .with(user.cn, :admin).and_return(nil)
    allow_any_instance_of(User).to receive(:ldap_entry)
      .and_return({ uid: user.cn, mail: user.email, display_name: "Freddy" })
    allow_any_instance_of(LdapManager::FetchAvatar).to receive(:call)
      .and_return(nil)

    login_as admin, :scope => :user
  end

  describe "User details page" do
    before do
      visit admin_user_path("alfred")
    end

    it "shows the user info" do
      within "h1" do
        expect(page).to have_content("User: alfred")
      end
      expect(page).to have_content("alfred@example.com")
    end
  end

  scenario 'Add invitations to account' do
    visit admin_user_path("alfred")
    find("#add-invitations").click

    select "5", :from => "amount"
    uncheck "notify_user"
    click_button "Add"

    expect(user.invitations.count).to eq(5)
  end

  scenario 'Remove invitations from account' do
    3.times { Invitation.create(user: user) }
    expect(user.invitations.count).to eq(3)

    visit admin_user_path("alfred")
    find("#remove-invitations").click

    expect(user.invitations.count).to eq(0)
  end
end
