-- Ensure platform role assignments are unique when community_id IS NULL

DELETE FROM user_roles a
USING user_roles b
WHERE a.community_id IS NULL
  AND b.community_id IS NULL
  AND a.user_id = b.user_id
  AND a.role_id = b.role_id
  AND a.id > b.id;

CREATE UNIQUE INDEX IF NOT EXISTS idx_user_roles_unique_platform
ON user_roles (user_id, role_id)
WHERE community_id IS NULL;
