CREATE OR REPLACE FUNCTION replace_placeholder_variables(
    input_text TEXT,
    variables JSONB
) RETURNS TEXT AS $$
DECLARE
    key TEXT;
    val TEXT;
BEGIN
    BEGIN
        RAISE NOTICE 'INPUT TEXT: %, VARIABLES: %', input_text, variables;

        -- Loop through each key-value pair in the JSONB object
        FOR key, val IN
            SELECT k, variables ->> k
            FROM jsonb_object_keys(variables) AS k
        LOOP
            RAISE NOTICE 'Replacing % with %', key, val;
            input_text := replace(input_text, key, val);
        END LOOP;

        RETURN input_text;

    EXCEPTION
        WHEN OTHERS THEN
            -- If any error occurs, return the original input_text
            RAISE NOTICE 'Error occurred, returning input text unchanged';
            RETURN input_text;
    END;
END;
$$ LANGUAGE plpgsql;