SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci;

USE hyapp_user;

CREATE TABLE IF NOT EXISTS manager_profiles (
  app_code VARCHAR(32) NOT NULL DEFAULT 'lalu' COMMENT '应用编码，用于多租户隔离',
  user_id BIGINT NOT NULL PRIMARY KEY COMMENT '经理用户 ID',
  status VARCHAR(32) NOT NULL COMMENT '业务状态',
  contact_info VARCHAR(128) NOT NULL DEFAULT '' COMMENT '联系信息',
  created_by_admin_id BIGINT NOT NULL DEFAULT 0 COMMENT '创建后台管理员 ID',
  created_at_ms BIGINT NOT NULL COMMENT '创建时间，UTC epoch ms',
  updated_at_ms BIGINT NOT NULL COMMENT '更新时间，UTC epoch ms',
  KEY idx_manager_profiles_status (app_code, status, updated_at_ms),
  KEY idx_manager_profiles_created_by (app_code, created_by_admin_id, created_at_ms)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='经理资料表';

SET @ddl := IF(
  (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'manager_profiles' AND COLUMN_NAME = 'contact_info') = 0,
  'ALTER TABLE manager_profiles ADD COLUMN contact_info VARCHAR(128) NOT NULL DEFAULT '''' COMMENT ''联系信息'' AFTER status',
  'SELECT 1'
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

INSERT INTO manager_profiles (
  app_code, user_id, status, contact_info, created_by_admin_id, created_at_ms, updated_at_ms
)
SELECT
  bl.app_code,
  bl.created_by_user_id,
  'active',
  '',
  0,
  MIN(bl.created_at_ms),
  MAX(bl.updated_at_ms)
FROM bd_leader_profiles bl
JOIN users u
  ON u.app_code = bl.app_code
 AND u.user_id = bl.created_by_user_id
WHERE bl.created_by_user_id > 0
GROUP BY bl.app_code, bl.created_by_user_id
ON DUPLICATE KEY UPDATE
  updated_at_ms = GREATEST(manager_profiles.updated_at_ms, VALUES(updated_at_ms));
