DELIMITER $$
CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`manaSpellers_requery`(
	vDepartmentFk INTEGER
)
`whole_proc`:
BEGIN
/**
 * Guarda en departmentMana el mana consumido por un departamento
 *
 * @param vDepartmentFk Id department
 */
	DECLARE vIsDepartmentExcluded BOOLEAN;

	SELECT COUNT(*) INTO vIsDepartmentExcluded
		FROM departmentManaExcluded
		WHERE departmentFk = vSalesDepartmentFk;

	IF vIsDepartmentExcluded THEN
		LEAVE whole_proc;
	END IF;

	CREATE OR REPLACE TEMPORARY TABLE tmp.client
		SELECT id
			FROM client 
			WHERE salesDepartmentFk = vDepartmentFk;

	CALL client_getMana();

	INSERT INTO departmentMana (departmentFk, amount)
		SELECT vDepartmentFk, SUM(mana)
			FROM tmp.clientMana
			ON DUPLICATE KEY UPDATE amount = VALUES(amount);

	DROP TEMPORARY TABLE 
		tmp.client,
		tmp.clientMana;
END$$
DELIMITER ;
