-- Cascade: City filtered by State on Add Lead activity (app 385)
-- Activity 26398, workflow_version 29852  (config row id 405)
-- State field = state_region_input (-> States dataset, value_key=state)
-- City  field = city_input         (-> Cities dataset, display=city, value=city_id)
--
-- Appends a filter_options rule to City: show only Cities rows where
-- Cities.state == current value of the State field.
-- Idempotent: skips if a rule with id 'rule_city_by_state' already exists.

BEGIN;

UPDATE workflow.tbl_wf_activity_ui_config
SET field_rules = COALESCE(field_rules, '[]'::jsonb) || '[
  {
    "id": "rule_city_by_state",
    "action": "filter_options",
    "active": true,
    "conditions": null,
    "action_value": null,
    "target_field": "city_input",
    "filter_config": {
      "logic": "AND",
      "conditions": [
        {
          "operator": "equals",
          "form_field": "state_region_input",
          "target_column": "state",
          "source_value_key": ""
        }
      ]
    }
  }
]'::jsonb,
    updated_at = now()
WHERE activity_id = 26398
  AND workflow_version_id = 29852
  AND NOT COALESCE(field_rules, '[]'::jsonb) @> '[{"id": "rule_city_by_state"}]'::jsonb;

-- Verify (expect the new rule present)
SELECT id, activity_id, jsonb_pretty(field_rules) AS field_rules
FROM workflow.tbl_wf_activity_ui_config
WHERE activity_id = 26398 AND workflow_version_id = 29852;

COMMIT;
