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

PREPARE stmt FROM @add_coin_seller_contact_info;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @add_coin_seller_sub_permission := (
  SELECT IF(
    COUNT(*) = 0,
    'ALTER TABLE coin_seller_profiles ADD COLUMN can_manage_sub_coin_sellers TINYINT(1) NOT NULL DEFAULT 1 COMMENT ''是否允许在币商中心管理直属子币商'' AFTER contact_info',
    'SELECT 1'
  )
  FROM information_schema.COLUMNS
  WHERE TABLE_SCHEMA = DATABASE()
    AND TABLE_NAME = 'coin_seller_profiles'
    AND COLUMN_NAME = 'can_manage_sub_coin_sellers'
);

PREPARE stmt FROM @add_coin_seller_sub_permission;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

CREATE TABLE IF NOT EXISTS coin_seller_relations (
  app_code VARCHAR(32) NOT NULL DEFAULT 'lalu' COMMENT '应用编码，用于多租户隔离',
  relation_id BIGINT NOT NULL PRIMARY KEY COMMENT '直属关系 ID',
  parent_user_id BIGINT NOT NULL COMMENT '父币商用户 ID',
  child_user_id BIGINT NOT NULL COMMENT '子币商用户 ID',
  status VARCHAR(32) NOT NULL DEFAULT 'active' COMMENT '关系状态',
  created_by_user_id BIGINT NOT NULL COMMENT '创建人用户 ID',
  created_at_ms BIGINT NOT NULL COMMENT '创建时间，UTC epoch ms',
  updated_at_ms BIGINT NOT NULL COMMENT '更新时间，UTC epoch ms',
  active_child_user_id BIGINT GENERATED ALWAYS AS (
    CASE WHEN status = 'active' THEN child_user_id ELSE NULL END
  ) STORED COMMENT '当前有效子币商用户 ID',
  UNIQUE KEY uk_coin_seller_relation_active_child (app_code, active_child_user_id),
  UNIQUE KEY uk_coin_seller_relation_parent_child_status (app_code, parent_user_id, child_user_id, status),
  KEY idx_coin_seller_relation_parent (app_code, parent_user_id, status, created_at_ms),
  KEY idx_coin_seller_relation_child (app_code, child_user_id, status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='币商直属子币商关系表';
