require 'rest'

module RestColores
  class Application
    ["positions"].each do |base_path|
      get "/#{base_path}" do
        RestColores::Models::Position.all.as_json(include: :requirements)
      end
      
      get "/#{base_path}/:id" do
        RestColores::Models::Position.find(params["id"]).as_json(include: :requirements)
      end
      
      post "/#{base_path}" do
        position = RestColores::Models::Position.new @request_body
        
        if position.save
          headers \
            "Location" => request.host_with_port + "/#{base_path}/#{position.id}"
          status 201
        else
          error 400, ["Could not save Position"] + position.errors.full_messages
        end
      end
      
      delete "/#{base_path}/:id" do
        if (RestColores::Models::Position.delete(params["id"]) == 0)
          error 400, "Position does not exist"
        end
        status 204
      end
    end
  end
end
