CREATE OR REPLACE FUNCTION replace_values(
  input_json JSONB
)
RETURNS JSONB AS $$
DECLARE
  placeholder TEXT;
  value_json JSONB;
  resolved_value JSONB;
BEGIN
  placeholder := input_json ->> 'placeholder';
  value_json := input_json -> 'value_json';

  BEGIN
    -- Check if key exists
    IF value_json ? placeholder THEN
        resolved_value := value_json -> placeholder;  -- ✅ PRESERVE TYPE (JSONB)
        RETURN jsonb_build_object('value', resolved_value);
    END IF;

    -- Fallback → return placeholder as TEXT
    RETURN jsonb_build_object('value', to_jsonb(placeholder));

  EXCEPTION
    WHEN OTHERS THEN
      RETURN jsonb_build_object('value', to_jsonb(placeholder));
  END;
END;
$$ LANGUAGE plpgsql;