CREATE OR REPLACE FUNCTION replace_placeholder_variables(
    input_text TEXT,
    variables JSONB
) RETURNS TEXT AS $$
DECLARE
    key TEXT;
    val TEXT;
BEGIN
    -- 🔒 Protect against NULL query
    IF input_text IS NULL THEN
        RAISE NOTICE 'Input text is NULL';
        RETURN NULL;
    END IF;

    RAISE NOTICE 'INPUT TEXT: %, VARIABLES: %', input_text, variables;

    FOR key, val IN
        SELECT k, variables ->> k
        FROM jsonb_object_keys(variables) AS k
    LOOP
        -- 🔒 Skip NULL values (CRITICAL FIX)
        IF val IS NOT NULL THEN
            RAISE NOTICE 'Replacing % with %', key, val;
            input_text := replace(input_text, key, val);
        ELSE
            RAISE NOTICE 'Skipping % because value is NULL', key;
        END IF;
    END LOOP;

    RETURN input_text;

EXCEPTION
    WHEN OTHERS THEN
        RAISE NOTICE 'Error occurred, returning input text unchanged';
        RETURN input_text;
END;
$$ LANGUAGE plpgsql;