DROP PROCEDURE IF EXISTS mocha_prepare_instance;

CREATE PROCEDURE mocha_prepare_instance
(
    IN p_class_inst_id INT,
    IN p_inst_id INT,
    IN p_class_global_identifier CHAR(32), -- the global identifier of the class of the newly created instance
    IN p_global_identifier CHAR(32), -- the desired global identifier for the newly created instance
    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 p_class_index INT;

    DECLARE z_global_identifier CHAR(32);
    DECLARE z_effective_date DATETIME;

    SET p_tenant_id = mocha_get_current_tenant();

    -- SET p_class_index = (SELECT inst_id FROM mocha_instances WHERE tenant_id = p_tenant_id AND class_id = 1 AND id = p_class_inst_id);

    SET p_class_index = p_class_inst_id;
    IF p_class_index IS NULL AND NOT p_class_global_identifier IS NULL THEN

        SET p_class_index = (SELECT inst_id FROM mocha_instances WHERE tenant_id = p_tenant_id AND id = mocha_get_instance_by_global_identifier(p_class_global_identifier));

    END IF;

    -- IF p_class_index IS NULL THEN

    --     SELECT "cannot create an instance of something that is not a Class" AS error_description;
    --     LEAVE sp;

    -- END IF;

    SET next_inst_id=p_inst_id;
    IF p_inst_id IS NULL THEN
        SET next_inst_id = mocha_get_next_inst_id(p_class_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();

    -- -- then update relationship: Class.has Instance
    -- CALL mocha_assign_relationship
    -- (
    --     mocha_get_instance_by_key(1, p_class_index),
    --     mocha_get_instance_by_global_identifier('7EB41D3C2AE9488483A4E59441BCAEFB'),
    --     mocha_get_instance_by_key(p_class_index, next_inst_id),
    --     p_user_inst_id,
    --     z_effective_date
    -- );
    -- -- then update relationship: Instance.for Class
    -- CALL mocha_assign_relationship
    -- (
    --     mocha_get_instance_by_key(p_class_index, next_inst_id),
    --     mocha_get_instance_by_global_identifier('494D5A6D04BE477B8763E3F57D0DD8C8'),
    --     mocha_get_instance_by_key(1, p_class_index),
    --     p_user_inst_id,
    --     z_effective_date
    -- );

END;
