-- Map tenant_id for Workplace Registration Review invoice creation
INSERT INTO workflow_steps (workflow_id, step_order, step_type, config)
SELECT w.id, 2, 'map_fields', '{"map":{"tenant_id":"tenant_id"}}'
FROM workflows w
WHERE w.name='Workplace Registration Review'
  AND NOT EXISTS (
    SELECT 1 FROM workflow_steps ws
    WHERE ws.workflow_id = w.id AND ws.step_order = 2 AND ws.step_type='map_fields'
  );

-- Move invoice creation to follow mapping step
UPDATE workflow_steps
SET step_order = 3
WHERE workflow_id = (SELECT id FROM workflows WHERE name='Workplace Registration Review')
  AND step_type = 'create_invoice';

-- Shift invoice preview modal
UPDATE workflow_steps
SET step_order = 4
WHERE workflow_id = (SELECT id FROM workflows WHERE name='Workplace Registration Review')
  AND step_type = 'open_modal'
  AND config->>'modal' = 'Workplace Invoice Preview';

-- Shift notice preview modal if present
UPDATE workflow_steps
SET step_order = 5
WHERE workflow_id = (SELECT id FROM workflows WHERE name='Workplace Registration Review')
  AND step_type = 'open_modal'
  AND config->>'modal' = 'Workplace Notice Preview';

-- Ensure sequence is correct
SELECT setval('workflow_steps_id_seq', (SELECT MAX(id) FROM workflow_steps));
