module Features
  root = File.dirname(File.dirname(__FILE__))
  Dir[File.join(File.join(root, "twirp"), "**/*.rb")].each do |file|
    require file
  end

  module SessionHelpers
    def sign_in
      # this is a no-op with mocked omniauth
    end

    class Configuration
      include Code::Justin::Tv::Sse::Sandstorm

      def self.ldap_username
        ldap_credentials['username']
      end

      def self.ldap_password
        ldap_credentials['password']
      end

      def self.ldap_credentials
        @ldap_credentials ||= fetch_ldap_credentials
        @ldap_credentials
      end

      def self.fetch_ldap_credentials
        res = client.get_decrypted_secret(
          GetDecryptedSecretReq.new(
            name: secret_key(key: 'integration-test-ldap-user.json')
          )
        )

        raise res.error.to_s if res.error
        JSON.parse(res.data.plaintext)
      end

      def self.client
        @client ||= SandstormClient.new(connection)
        @client
      end

      def self.connection
        Faraday.new('unix:///twirp/') do |f|
          f.adapter :excon, {
            socket: Settings.sandstorm_addr,
            connect_timeout: 60,
            read_timeout: 60,
          }
        end
      end

      def self.secret_key(options = {})
        group = options[:group] || 'admin-platform'
        project = options[:project] || 'admin-panel'
        environment = options[:environment] || 'staging'
        key = options[:key]
        return [group, project, environment, key].join('/')
      end

      private_class_method :client
      private_class_method :connection
      private_class_method :fetch_ldap_credentials
      private_class_method :ldap_credentials
      private_class_method :secret_key
    end
  end
end
