module Devops
  module API3
    module Routes
      module ChefRoutes

        def self.registered(app)

          app.define_policy :read_chef, "Read data for chef configuration manager"
          app.define_policy :modify_chef_tags, "Change tags for nodes in chef configuration manager"

          # Get list of available bootstrap templates
          app.get_with_headers "/chef/bootstrap_templates" do
            check_policy(:read_chef)
            json Devops::API3::Handler::Chef.new(request).get_bootstrap_templates
          end

          app.get_with_headers "/chef/nodes" do
            check_policy(:read_chef)
            json Devops::API3::Handler::Chef.new(request).chef_nodes
          end

          # Get tags list for :node_name
          app.get_with_headers "/chef/tags/:cm_name" do |cm_name|
            check_policy(:read_chef)
            json Devops::API3::Handler::Tag.new(request).tags(cm_name)
          end

          # Set tags list to :node_name
          app.post_with_headers "/chef/tags/:cm_name/set" do |cm_name|
            check_policy(:modify_chef_tags)
            tags = Devops::API3::Handler::Tag.new(request).set_tags(cm_name)
            create_response("Set tags for #{cm_name}", tags: tags)
          end

          # Delete tags from :node_name
          app.post_with_headers "/chef/tags/:cm_name/unset" do |cm_name|
            check_policy(:modify_chef_tags)
            tags = Devops::API3::Handler::Tag.new(request).unset_tags(cm_name)
            create_response("Deleted tags for #{cm_name}", tags: tags)
          end

          puts "Chef routes initialized"
        end

      end
    end
  end
end

