-- Cleanup phantom Schedule-page agents (app 385, sandbox)
-- Junk test rows where owner_agent is a bare placeholder string instead of {id,name}.
-- Effect: nulls owner_agent -> these leads collapse into "Unassigned" on the Schedule page.
-- Affected instances: 4489 (Sandy), 4490 (Alex), 4502 (Owner Agent), 4511/4512 (Owner Agent*)
--
-- NOTE: recordview reads from the denormalized companion table
-- tbl_wf_385_lead_to_policy, which is kept in sync only via the app write path.
-- A raw UPDATE to tbl_appdata_workflow_instances does NOT propagate, so we must
-- clean BOTH tables.

BEGIN;

-- Preview before committing
SELECT 'main' AS tbl, instance_id, data->'owner_agent' AS owner_agent
FROM public.tbl_appdata_workflow_instances
WHERE instance_id IN (4489, 4490, 4502, 4511, 4512)
UNION ALL
SELECT 'companion', instance_id, owner_agent
FROM public.tbl_wf_385_lead_to_policy
WHERE instance_id IN (4489, 4490, 4502, 4511, 4512);

-- 1. Main instance table: drop the bad owner_agent key (only bare-string placeholders)
UPDATE public.tbl_appdata_workflow_instances
SET data = data - 'owner_agent',
    updated_at = now()
WHERE instance_id IN (4489, 4490, 4502, 4511, 4512)
  AND jsonb_typeof(data->'owner_agent') = 'string';

-- 2. Companion recordview table: null out the bad owner_agent (only bare-string placeholders)
UPDATE public.tbl_wf_385_lead_to_policy
SET owner_agent = NULL
WHERE instance_id IN (4489, 4490, 4502, 4511, 4512)
  AND jsonb_typeof(owner_agent) = 'string';

-- Verify (should return 0 rows)
SELECT 'main' AS tbl, instance_id FROM public.tbl_appdata_workflow_instances
WHERE instance_id IN (4489, 4490, 4502, 4511, 4512) AND data ? 'owner_agent'
UNION ALL
SELECT 'companion', instance_id FROM public.tbl_wf_385_lead_to_policy
WHERE instance_id IN (4489, 4490, 4502, 4511, 4512) AND owner_agent IS NOT NULL;

COMMIT;
