class CreateLdapUserJob < ApplicationJob
  queue_as :default

  def perform(username, domain, email, hashed_pw)
    dn = "cn=#{username},ou=#{domain},cn=users,dc=kosmos,dc=org"
    attr = {
      objectclass: ["top", "account", "person", "extensibleObject"],
      cn: username,
      sn: username,
      uid: username,
      mail: email,
      userPassword: hashed_pw
    }

    ldap_client.add(dn: dn, attributes: attr)
  end

  def ldap_client
    ldap_client ||= Net::LDAP.new host: ldap_config['host'],
      port: ldap_config['port'],
      # encryption: ldap_config['ssl'],
      auth: {
        method: :simple,
        username: ldap_config['admin_user'],
        password: ldap_config['admin_password']
      }
  end

  def ldap_config
    ldap_config ||= YAML.load(ERB.new(File.read("#{Rails.root}/config/ldap.yml")).result)[Rails.env]
  end
end
