USE hyapp_wallet;

-- 金币流水和统计回放按 app/asset/user/time 顺序读取 wallet_entries；
-- 这个索引让单资产余额回放和用户金币流水命中同一条有序访问路径，避免全表扫描后排序。
SET @ddl := IF(
  (SELECT COUNT(*) FROM information_schema.STATISTICS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'wallet_entries' AND INDEX_NAME = 'idx_wallet_entries_asset_user_time') = 0,
  'ALTER TABLE wallet_entries ADD INDEX idx_wallet_entries_asset_user_time (app_code, asset_type, user_id, created_at_ms, entry_id)',
  'SELECT 1'
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
