SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci;

USE hyapp_user;

-- 粉丝数是资料卡高频读模型，新列使用 INSTANT DDL 只修改数据字典，
-- 避免资料卡每次打开都反向 COUNT user_follows。条件 DDL 保持重复执行安全。
SET @ddl := IF(
  (SELECT COUNT(*) FROM information_schema.COLUMNS
   WHERE TABLE_SCHEMA = DATABASE()
     AND TABLE_NAME = 'user_profile_stats'
     AND COLUMN_NAME = 'followers_count') = 0,
  'ALTER TABLE user_profile_stats
     ADD COLUMN followers_count BIGINT NOT NULL DEFAULT 0 COMMENT ''粉丝数量'' AFTER following_count,
     ALGORITHM=INSTANT',
  'SELECT 1'
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- 一次按现存 active 关注边回填；分组读取复用
-- idx_user_follows_followee_status(app_code, followee_user_id, status, updated_at_ms)，
-- ON DUPLICATE KEY 同时覆盖已有投影并补齐历史上缺失的被关注者投影行。
INSERT INTO user_profile_stats (
  app_code,
  user_id,
  visitors_count,
  following_count,
  followers_count,
  friends_count,
  updated_at_ms
)
SELECT
  app_code,
  followee_user_id,
  0,
  0,
  COUNT(*),
  0,
  MAX(updated_at_ms)
FROM user_follows FORCE INDEX (idx_user_follows_followee_status)
WHERE status = 'active'
GROUP BY app_code, followee_user_id
ON DUPLICATE KEY UPDATE
  followers_count = VALUES(followers_count),
  updated_at_ms = GREATEST(user_profile_stats.updated_at_ms, VALUES(updated_at_ms));
