DROP PROCEDURE IF EXISTS mocha_create_user;

CREATE PROCEDURE mocha_create_user
(
	IN p_username VARCHAR(32),
	IN p_global_identifier CHAR(32)
)
sp: BEGIN

	DECLARE z_global_identifier CHAR(32);

    IF p_global_identifier IS NULL THEN
        SET z_global_identifier=mocha_uuid_v4();
    ELSE
        SET z_global_identifier=p_global_identifier;
    END IF;

	SET @user_iid = mocha_get_user_by_username(p_username);
	IF @user_iid IS NULL THEN
		CALL mocha_create_instance_of(mocha_get_instance_by_global_identifier('9C6871C19A7F4A3A900E69D1D9E24486'), z_global_identifier, NULL, NULL, @user_iid);
	ELSE
        SELECT "user with the specified name already exists on this tenant" AS error_description;
        LEAVE sp;
    END IF;

	SELECT @user_iid;

	CALL mocha_set_attribute_value(@user_iid, mocha_get_instance_by_global_identifier('960FAF025C5940F791A720012A99D9ED'), p_username, NULL, NULL);

END;