require 'rails_helper'

RSpec.describe CreateLdapUserJob, type: :job do
  let(:ldap_client_mock) { instance_double(Net::LDAP) }

  before do
    allow_any_instance_of(described_class).to receive(:ldap_client).and_return(ldap_client_mock)
  end

  subject(:job) {
    described_class.perform_later(
      username: 'halfinney', domain: 'kosmos.org',
      email: 'halfinney@example.com',
      hashed_pw: 'remember-remember-the-5th-of-november'
    )
  }

  subject(:job_for_preconfirmed_account) {
    described_class.perform_later(
      username: 'halfinney', domain: 'kosmos.org',
      email: 'halfinney@example.com',
      hashed_pw: 'remember-remember-the-5th-of-november',
      confirmed: true
    )
  }

  it "creates a new document with the correct attributes" do
    allow(ldap_client_mock).to receive(:add) # spy on mock

    perform_enqueued_jobs { job }

    expect(ldap_client_mock).to have_received(:add).with(
      dn: "cn=halfinney,ou=kosmos.org,cn=users,dc=kosmos,dc=org",
      attributes: {
        objectclass: ["top", "account", "person", "extensibleObject"],
        cn: "halfinney",
        sn: "halfinney",
        uid: "halfinney",
        mail: "halfinney@example.com",
        userPassword: "remember-remember-the-5th-of-november"
      }
    )
  end

  it "adds default services for pre-confirmed accounts" do
    allow(ldap_client_mock).to receive(:add) # spy on mock
    allow(Setting).to receive(:default_services).and_return(["xmpp", "discourse"])

    perform_enqueued_jobs { job_for_preconfirmed_account }

    expect(ldap_client_mock).to have_received(:add).with(
      dn: "cn=halfinney,ou=kosmos.org,cn=users,dc=kosmos,dc=org",
      attributes: {
        objectclass: ["top", "account", "person", "extensibleObject"],
        cn: "halfinney",
        sn: "halfinney",
        uid: "halfinney",
        mail: "halfinney@example.com",
        serviceEnabled: ["xmpp", "discourse"],
        userPassword: "remember-remember-the-5th-of-november"
      }
    )
  end

  after do
    clear_enqueued_jobs
    clear_performed_jobs
  end
end
