SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci;

-- 历史 admin_app_configs 没有租户列，所有 App 共同读取同一行。迁移把这些行保留为 app_code=''
-- 的只读默认基线：未知或未来新增 App 仍能读取原配置，后续写操作只创建当前 App 的 scoped override。
-- 早期 AutoMigrate 和 024 SQL 使用过两个不同的 legacy 唯一索引名；每一步均按元数据执行，
-- 使全新数据库、任一历史形态以及失败后重跑都收敛到同一三元唯一键。
SET @ddl := IF(
  (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'admin_app_configs' AND COLUMN_NAME = 'app_code') = 0,
  'ALTER TABLE admin_app_configs ADD COLUMN app_code VARCHAR(32) NOT NULL DEFAULT '''' COMMENT ''应用编码；空值仅表示迁移前的只读默认基线'' AFTER id',
  '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 = 'admin_app_configs' AND COLUMN_NAME = 'is_deleted') = 0,
  'ALTER TABLE admin_app_configs ADD COLUMN is_deleted BOOLEAN NOT NULL DEFAULT FALSE COMMENT ''当前 App 删除墓碑；用于屏蔽默认基线'' AFTER description',
  '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 = 'admin_app_configs' AND INDEX_NAME = 'uk_admin_app_configs_group_key') > 0,
  'ALTER TABLE admin_app_configs DROP INDEX uk_admin_app_configs_group_key',
  '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 = 'admin_app_configs' AND INDEX_NAME = 'idx_admin_app_config_group_key') > 0,
  'ALTER TABLE admin_app_configs DROP INDEX idx_admin_app_config_group_key',
  '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 = 'admin_app_configs' AND INDEX_NAME = 'uk_admin_app_config_app_group_key') = 0,
  'ALTER TABLE admin_app_configs ADD UNIQUE KEY uk_admin_app_config_app_group_key (app_code, `group`, `key`)',
  '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 = 'admin_app_configs' AND INDEX_NAME = 'idx_admin_app_configs_app_group') = 0,
  'ALTER TABLE admin_app_configs ADD KEY idx_admin_app_configs_app_group (app_code, `group`)',
  'SELECT 1'
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
