DROP PROCEDURE IF EXISTS mocha_create_class;

CREATE PROCEDURE mocha_create_class
(
    IN p_class_id INT,
    IN p_global_identifier CHAR(32),
    IN p_user_inst_id INT,
    IN p_effective_date DATETIME,
    OUT p_assigned_inst_id INT
)
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();

    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, 1, p_class_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;
