DROP PROCEDURE IF EXISTS mocha_create_instance;

CREATE PROCEDURE mocha_create_instance
(
    IN p_global_identifier CHAR(32), -- the desired global identifier for the newly created instance
	IN p_class_index INT,
	IN p_inst_index INT,

    IN p_user_inst_id INT,
    IN p_effective_date DATETIME,
    OUT p_assigned_inst_id INT
)
sp: BEGIN

    DECLARE p_tenant_id INT;
    DECLARE next_inst_id INT;

    DECLARE z_global_identifier CHAR(32);
    DECLARE z_effective_date DATETIME;

    SET p_tenant_id = mocha_get_current_tenant();

	IF p_inst_index IS NULL THEN
		SET next_inst_id = mocha_get_next_inst_id(p_class_index);
	ELSE
    	SET next_inst_id = p_inst_index;
	END IF;

    IF p_effective_date IS NULL THEN
        SET z_effective_date = NOW();
    ELSE
        SET z_effective_date = p_effective_date;
    END IF;

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

    -- insert record first
    INSERT INTO mocha_instances
    (tenant_id, class_id, inst_id, global_identifier)
    VALUES
    (p_tenant_id, p_class_index, next_inst_id, z_global_identifier);
    
    SET p_assigned_inst_id = LAST_INSERT_ID();

END;
