module Devops
  module API3
    module Routes
      module UserRoutes

        def self.registered(app)

          app.define_policy :read_users, "Read users list"
          app.define_policy :create_users, "Create new users"
          app.define_policy :delete_users, "Delete users"

          app.get_with_headers "/users" do
            check_policy(:read_users)
            json Devops::API3::Handler::User.new(request).users.map(&:to_hash)
          end

          app.post_with_headers "/user" do
            check_policy(:create_users)
            user = Devops::API3::Handler::User.new(request).create
            create_response("Created", {id: user.id}, 201)
          end

          app.post_with_headers %r{\A/user/(#{Devops::Model::User::USER_NAME_REGEX})/roles/add\z} do |user|
            check_policy(:create_users)
            user = Devops::API3::Handler::User.new(request).add_roles(user)
            create_response("Updated", {id: user.id}, 200)
          end

          app.post_with_headers %r{\A/user/(#{Devops::Model::User::USER_NAME_REGEX})/roles/delete\z} do |user|
            check_policy(:create_users)
            user = Devops::API3::Handler::User.new(request).delete_roles(user)
            create_response("Updated", {id: user.id}, 200)
          end

          hash = {}
          hash["DELETE"] = lambda {|user|
            check_policy(:delete_users)
            Devops::API3::Handler::User.new(request).delete(user)
            create_response("User '#{user}' has been deleted", {id: user})
          }

          hash["GET"] = lambda {|id|
            check_policy(:read_users)
            json Devops::API3::Handler::User.new(request).get_user(id).to_hash
          }
          hash["PUT"] = lambda {|id|
            check_policy(:create_users)
            Devops::API3::Handler::User.new(request).update_user(id)
            create_response("Updated", {id: id})
          }
          app.multi_routes %r{\A/user/(#{Devops::Model::User::USER_NAME_REGEX})\z}, hash

          app.put_with_headers %r{\A/user/(#{Devops::Model::User::USER_NAME_REGEX})/(email|password)\z} do |user, action|
            current_user = request.env['REMOTE_USER']
            check_policy(:create_users) unless current_user == user
            raise Devops::Exception::Unauthorized.new("Access denied for '#{current_user}'") if user == Devops::Model::User::ROOT_USER_NAME and current_user != Devops::Model::User::ROOT_USER_NAME
            Devops::API3::Handler::User.new(request).change(user, action)
            create_response("Updated", {id: user})
          end

          puts "User routes initialized"
        end

      end
    end
  end
end
