-- 外管团队 owner 和邀请父级必须由 user-service 持久化，不能由 admin-server 在列表时临时推导。
-- 所有新增列均为可空列，可在 MySQL 8 使用 INSTANT 添加；索引仍应在低峰期以 INPLACE 构建。
-- 启动兼容迁移也能先补列，因此离线脚本逐项探测，保证该发布步骤可安全重试。
SET @ddl := IF(
  (SELECT COUNT(*) FROM information_schema.COLUMNS
   WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'bd_profiles' AND COLUMN_NAME = 'parent_owner_user_id') = 0,
  'ALTER TABLE bd_profiles ADD COLUMN parent_owner_user_id BIGINT NULL COMMENT ''外管团队直接 owner 用户 ID；普通 App BD 始终为空'' AFTER parent_leader_user_id, ALGORITHM=INSTANT',
  'SELECT 1'
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- 历史和普通 App BD 必须保持 parent_owner_user_id=NULL。
-- 仅 ExternalInviteBD 的接受事务写该列，外管查询因此不会把 Lalu 的 BD Leader 树误纳入团队。

SET @ddl := IF(
  (SELECT COUNT(*) FROM information_schema.STATISTICS
   WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'bd_profiles' AND INDEX_NAME = 'idx_bd_profiles_parent_owner') = 0,
  'ALTER TABLE bd_profiles ADD INDEX idx_bd_profiles_parent_owner (app_code, parent_owner_user_id, status, user_id), ALGORITHM=INPLACE, LOCK=NONE',
  'SELECT 1'
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @ddl := IF(
  (SELECT COUNT(*) FROM information_schema.COLUMNS
   WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'role_invitations' AND COLUMN_NAME = 'external_operator_user_id') = 0,
  'ALTER TABLE role_invitations ADD COLUMN external_operator_user_id BIGINT NULL COMMENT ''外管邀请操作者的 App 用户 ID，普通 App 邀请为空'' AFTER target_user_id, ALGORITHM=INSTANT',
  'SELECT 1'
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @ddl := IF(
  (SELECT COUNT(*) FROM information_schema.COLUMNS
   WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'role_invitations' AND COLUMN_NAME = 'parent_owner_user_id') = 0,
  'ALTER TABLE role_invitations ADD COLUMN parent_owner_user_id BIGINT NULL COMMENT ''邀请创建时固化的外管团队 owner 用户 ID'' AFTER parent_leader_user_id, ALGORITHM=INSTANT',
  'SELECT 1'
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @ddl := IF(
  (SELECT COUNT(*) FROM information_schema.COLUMNS
   WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'role_invitations' AND COLUMN_NAME = 'parent_agency_id') = 0,
  'ALTER TABLE role_invitations ADD COLUMN parent_agency_id BIGINT NULL COMMENT ''Host 邀请创建时固化的 Agency ID'' AFTER parent_owner_user_id, ALGORITHM=INSTANT',
  'SELECT 1'
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @ddl := IF(
  (SELECT COUNT(*) FROM information_schema.STATISTICS
   WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'role_invitations' AND INDEX_NAME = 'idx_role_invitations_parent_owner') = 0,
  'ALTER TABLE role_invitations ADD INDEX idx_role_invitations_parent_owner (app_code, parent_owner_user_id, status, created_at_ms), ALGORITHM=INPLACE, LOCK=NONE',
  'SELECT 1'
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
