require "json"

module Devops
  module API3
    module Routes
      module KeyRoutes

        def self.registered(app)

          app.define_policy :read_keys, "Get keys list or key details"
          app.define_policy :create_keys, "Create keys"
          app.define_policy :delete_keys, "Delete keys"

          app.get_with_headers "/keys" do
            check_policy(:read_keys)
            json Devops::API3::Handler::Key.new(request).keys.map{|k| k.to_list_hash }
          end

          app.post_with_headers "/key" do
            check_policy(:create_keys)
            key = Devops::API3::Handler::Key.new(request).create(settings.keys_dir)
            create_response("Created", {id: key.id}, 201)
          end

          app.delete_with_headers "/key/:key" do |key|
            check_policy(:delete_keys)
            Devops::API3::Handler::Key.new(request).delete key
            create_response("Key '#{key}' has been removed", {id: key})
          end

          puts "Key routes initialized"
        end

      end
    end
  end
end
