module Devops
  module API3
    module Routes
      module StackTemplateRoutes

        def self.registered(app)

          app.define_policy :read_stack_templates, 'Read stack templates'
          app.define_policy :create_stack_templates, 'Create stack templates'
          app.define_policy :delete_stack_templates, 'Delete stack templates'

          app.get_with_headers '/stack_templates' do
            check_policy(:read_stack_templates)
            json Devops::API3::Handler::StackTemplate.new(request).stack_templates.map(&:to_hash)
          end

          app.get_with_headers '/stack_templates/provider/:provider' do |provider|
            check_policy(:read_stack_templates)
            check_provider(provider)
            json Devops::API3::Handler::StackTemplate.new(request).stack_templates_for_provider(provider).map(&:to_hash)
          end

          app.post_with_headers "/stack_template/:provider" do |provider|
            check_policy(:create_stack_templates)
            check_provider(provider)
            model = Devops::API3::Handler::StackTemplate.new(request).create_stack_template(provider)
            create_response 'Created', model.to_hash, 201
          end

          hash = {}

          hash['GET'] = lambda {|stack_template_id|
            check_policy(:read_stack_templates)
            json Devops::API3::Handler::StackTemplate.new(request).get_stack_template(stack_template_id).to_hash
          }

          hash['DELETE'] = lambda {|stack_template_id|
            check_policy(:delete_stack_templates)
            Devops::API3::Handler::StackTemplate.new(request).delete_stack_template(stack_template_id)
            create_response("Template '#{stack_template_id}' has been removed")
          }

          app.multi_routes '/stack_template/:stack_template_id', hash

          puts 'Stack_template routes initialized'
        end

      end
    end
  end
end
