-- Rebuild the State + City datasets from tbl_branches so every captured city is
-- always assignable (Create Lead → Assign cascade dependency).
--
-- App 385. Cities dataset=264, States dataset=265. City field=46815, State field=46814.
--
-- WHY: Assign Lead's region cascade matches  assign_city == tbl_branches.city  (city
-- NAMES), then owner agent by region. So the city captured at Create Lead must be a
-- branch city name. We therefore (a) source the City/State option lists straight from
-- tbl_branches, and (b) store the city NAME as the value (value_key=city), not city_id.
--
-- Datasets are read live from tbl_datasets (no redeploy needed for the data). The field
-- property changes live in the deployed workflow config, so REDEPLOY the version after
-- running this. Re-runnable: deterministic full rebuild from the current branches.

BEGIN;

-- Cities dataset ← distinct (state_name, city) from branches. keys: state, city.
UPDATE tbl_datasets
SET keys  = '["state","city"]'::jsonb,
    items = (
      SELECT COALESCE(
        jsonb_agg(jsonb_build_object('state', state_name, 'city', city) ORDER BY state_name, city),
        '[]'::jsonb)
      FROM (SELECT DISTINCT state_name, city FROM lead_to_policy.tbl_branches) t
    ),
    updated_at = now()
WHERE id = 264;

-- States dataset ← distinct state_name from branches. key: state.
UPDATE tbl_datasets
SET keys  = '["state"]'::jsonb,
    items = (
      SELECT COALESCE(
        jsonb_agg(jsonb_build_object('state', state_name) ORDER BY state_name),
        '[]'::jsonb)
      FROM (SELECT DISTINCT state_name FROM lead_to_policy.tbl_branches) t
    ),
    updated_at = now()
WHERE id = 265;

-- City field (46815): store the city NAME so it matches tbl_branches.city in the
-- Assign region cascade (and displays correctly).
UPDATE workflow.tbl_wf_fields
SET properties = jsonb_set(
      jsonb_set(properties, '{value_key}', '"city"'::jsonb),
      '{dataset_keys}', '["state","city"]'::jsonb)
WHERE id = 46815;

-- State field (46814): value + label + keys all on `state`.
UPDATE workflow.tbl_wf_fields
SET properties = jsonb_set(
      jsonb_set(
        jsonb_set(properties, '{value_key}', '"state"'::jsonb),
        '{display_keys}', '["state"]'::jsonb),
      '{dataset_keys}', '["state"]'::jsonb)
WHERE id = 46814;

-- Verify
SELECT id, name, jsonb_array_length(items) AS rows, keys FROM tbl_datasets WHERE id IN (264,265);
SELECT id, field_s_id,
       properties->>'value_key'   AS value_key,
       properties->'display_keys' AS display_keys
FROM workflow.tbl_wf_fields WHERE id IN (46814,46815);

COMMIT;
