module Rodauth::InternalRequestClassMethods

def internal_request(route, opts={}, &block)

def internal_request(route, opts={}, &block)
  opts = opts.dup
  
  env = {
     'REQUEST_METHOD'=>'POST',
     'PATH_INFO'=>'/'.dup,
     "SCRIPT_NAME" => "",
     "HTTP_HOST" => INVALID_DOMAIN,
     "SERVER_NAME" => INVALID_DOMAIN,
     "SERVER_PORT" => 443,
     "CONTENT_TYPE" => "application/x-www-form-urlencoded",
     "rack.input"=>StringIO.new(''),
     "rack.url_scheme"=>"https"
  }
  env.merge!(opts.delete(:env)) if opts[:env]
  session = {}
  session.merge!(opts.delete(:session)) if opts[:session]
  params = {}
  params.merge!(opts.delete(:params)) if opts[:params]
  scope = roda_class.new(env)
  rodauth = new(scope)
  rodauth.session = session
  rodauth.params = params
  rodauth.internal_request_block = block
  unless account_id = opts.delete(:account_id)
    if (account_login = opts.delete(:account_login))
      if (account = rodauth.send(:_account_from_login, account_login))
        account_id = account[rodauth.account_id_column]
      else
        raise InternalRequestError, "no account for login: #{account_login.inspect}"
      end
    end
  end
  if account_id
    session[rodauth.session_key] = account_id
    unless authenticated_by = opts.delete(:authenticated_by)
      authenticated_by = case route
      when :otp_auth, :sms_request, :sms_auth, :recovery_auth, :webauthn_auth, :webauthn_auth_params, :valid_otp_auth?, :valid_sms_auth?, :valid_recovery_auth?
        ['internal1']
      else
        ['internal1', 'internal2']
      end
    end
    session[rodauth.authenticated_by_session_key] = authenticated_by
  end
  opts.keys.each do |k|
    meth = :"#{k}_param"
    params[rodauth.public_send(meth).to_s] = opts.delete(k) if rodauth.respond_to?(meth)
  end
  unless opts.empty?
    warn "unhandled options passed to #{route}: #{opts.inspect}"
  end
  rodauth.handle_internal_request(:"_handle_#{route}")
end