-- Feed Mixing, Delivery Notes, Analytics and AI Assistant became their OWN role
-- permissions (previously folded into Feed / Sales / Reports). Copy each existing
-- custom role's parent-bucket permission into the new module so NO role loses the
-- access it already had:
--   feedMixing    <- feed
--   deliveryNotes <- sales
--   analytics     <- reports
--   aiAssistant   <- reports
-- The built-in Admin role (is_system = 1) always grants every module (computed in
-- Auth::effectivePermissions), so it needs nothing here and is skipped.
--
-- Idempotent: each row is only touched when the parent exists and the new key
-- isn't already present, so re-running is a no-op.

UPDATE roles SET permissions = JSON_SET(permissions, '$.feedMixing', JSON_EXTRACT(permissions, '$.feed'))
  WHERE is_system = 0 AND JSON_EXTRACT(permissions, '$.feed') IS NOT NULL AND JSON_EXTRACT(permissions, '$.feedMixing') IS NULL;

UPDATE roles SET permissions = JSON_SET(permissions, '$.deliveryNotes', JSON_EXTRACT(permissions, '$.sales'))
  WHERE is_system = 0 AND JSON_EXTRACT(permissions, '$.sales') IS NOT NULL AND JSON_EXTRACT(permissions, '$.deliveryNotes') IS NULL;

UPDATE roles SET permissions = JSON_SET(permissions, '$.analytics', JSON_EXTRACT(permissions, '$.reports'))
  WHERE is_system = 0 AND JSON_EXTRACT(permissions, '$.reports') IS NOT NULL AND JSON_EXTRACT(permissions, '$.analytics') IS NULL;

UPDATE roles SET permissions = JSON_SET(permissions, '$.aiAssistant', JSON_EXTRACT(permissions, '$.reports'))
  WHERE is_system = 0 AND JSON_EXTRACT(permissions, '$.reports') IS NOT NULL AND JSON_EXTRACT(permissions, '$.aiAssistant') IS NULL;
