require "db/mongo/models/role"
require "app/api3/parsers/roles"
require_relative "request_handler"

module Devops
  module API3
    module Handler
      class Roles < RequestHandler

        set_parser Devops::API3::Parser::RolesParser

        def policies
          Devops::Api3.policies.values
        end

        def roles
          Devops::Model::Role.all
        end

        def role id
          Devops::Model::Role.find(id)
        rescue Mongoid::Errors::DocumentNotFound
          raise Devops::Exception::RecordNotFound.new("Role with id '#{id}' not found")
        end

        def create_role
          Devops::Model::Role.create!(parser.create)
        rescue Mongoid::Errors::Validations => e
          raise Devops::Exception::ValidationError.create_from_db_exception(e)
        end

        def add_policies role_id
          list_to_add = parser.policies
          db_role = role(role_id)
          db_role.add_to_set({policies: list_to_add})
        end

        def delete_policies role_id
          list_to_pull = parser.policies
          db_role = role(role_id)
          db_role.pull_all({policies: list_to_pull})
        end

        def delete_role id
          role = role(id)
          users = []
          Devops::Model::User.where(roles: id).each do |u|
            users.push u.id
          end
          unless users.empty?
            raise Devops::Exception::ConflictError.new("Role '#{role.name}' used with users '#{users.join("', '")}'")
          end
          role.delete
        end

      end
    end
  end
end

