DROP PROCEDURE IF EXISTS mocha_get_instance_by_global_identifier;

CREATE PROCEDURE mocha_get_instance_by_global_identifier
(
    IN p_global_identifier CHAR(40)
)
BEGIN
    DECLARE p_tenant_id INT;

    SET p_tenant_id = mocha_get_current_tenant();

    SELECT * FROM mocha_instances
    WHERE (tenant_id = p_tenant_id OR tenant_id IN (SELECT target_tenant_id FROM mocha_tenant_references WHERE source_tenant_id = p_tenant_id))
    
    AND UPPER(global_identifier) = UPPER(REPLACE(REPLACE(REPLACE(p_global_identifier, '{', ''), '}', ''), '-', ''))
    ORDER BY id DESC
    LIMIT 1;

END;
