module Devops
  module API3
    module Routes
      module RolesRoutes

        def self.registered(app)

          app.define_policy :read_roles, "Read roles and available policies"
          app.define_policy :create_roles, "Create new roles"
          app.define_policy :delete_roles, "Delete roles"

          app.get_with_headers "/security/policies" do
            check_policy(:read_roles)
            json Devops::API3::Handler::Roles.new(request).policies.map{|p| p.to_hash}
          end

          app.get_with_headers "/security/roles" do
            check_policy(:read_roles)
            json Devops::API3::Handler::Roles.new(request).roles.map(&:to_hash)
          end

          app.post_with_headers "/security/role" do
            check_policy(:create_roles)
            role = Devops::API3::Handler::Roles.new(request).create_role()
            create_response "Created", {id: role.id}, 201
          end

          hash = {}
          hash["GET"] = lambda {|id|
            check_policy(:read_roles)
            json Devops::API3::Handler::Roles.new(request).role(id).to_hash
          }

          hash["DELETE"] = lambda {|id|
            check_policy(:delete_roles)
            Devops::API3::Handler::Roles.new(request).delete_role(id)
            create_response "Deleted", {id: id}, 200
          }

          app.multi_routes "/security/role/:id", hash

          app.post_with_headers "/security/role/:id/policies/add" do |role_id|
            check_policy(:create_roles)
            Devops::API3::Handler::Roles.new(request).add_policies(role_id)
            create_response "Updated", {id: role_id}
          end

          app.post_with_headers "/security/role/:id/policies/delete" do |role_id|
            check_policy(:create_roles)
            Devops::API3::Handler::Roles.new(request).delete_policies(role_id)
            create_response "Updated", {id: role_id}
          end

          puts "Roles routes initialized"
        end

      end
    end
  end
end
