require 'rails_helper'

RSpec.describe 'E-Mail settings', type: :feature do
  let(:user) { create :user }

  feature "Reset email password" do
    before do
      login_as user, :scope => :user

      allow_any_instance_of(User).to receive(:valid_ldap_authentication?)
        .with("invalid password").and_return(false)
      allow_any_instance_of(User).to receive(:valid_ldap_authentication?)
        .with("valid password").and_return(true)
    end

    scenario 'fails with invalid password' do
      expect(LdapManager::UpdateEmailPassword).not_to receive(:call)
      expect(LdapManager::UpdateEmailMaildrop).not_to receive(:call)

      visit setting_path(:email)
      fill_in 'Current account password', with: "invalid password"
      click_button "Create new email password"

      within ".error-msg" do
        expect(page).to have_content("Wrong password")
      end
    end

    scenario 'works with valid password' do
      allow_any_instance_of(User).to receive(:dn)
        .and_return("cn=#{user.cn},ou=kosmos.org,cn=users,dc=kosmos,dc=org")
      allow_any_instance_of(User).to receive(:ldap_entry)
        .and_return({ uid: user.cn, ou: user.ou, email_maildrop: user.address })

      expect(LdapManager::UpdateEmailPassword).to receive(:call).and_return(true)
      expect(LdapManager::UpdateEmailMaildrop).not_to receive(:call)

      visit setting_path(:email)
      fill_in 'Current account password', with: "valid password"
      click_button "Create new email password"

      expect(current_url).to eq(new_password_services_email_url)
    end

    scenario 'updates the maildrop attribute if necessary' do
      allow_any_instance_of(User).to receive(:dn)
        .and_return("cn=#{user.cn},ou=kosmos.org,cn=users,dc=kosmos,dc=org")
      allow_any_instance_of(User).to receive(:ldap_entry)
        .and_return({ uid: user.cn, ou: user.ou, email_maildrop: "mahafaly@example.com" })

      expect(LdapManager::UpdateEmailPassword).to receive(:call).and_return(true)
      expect(LdapManager::UpdateEmailMaildrop).to receive(:call)
        .with(dn: user.dn, address: user.address).and_return(true)

      visit setting_path(:email)
      fill_in 'Current account password', with: "valid password"
      click_button "Create new email password"

      expect(current_url).to eq(new_password_services_email_url)
    end
  end
end
