package mysql

import "context"

func (r *Repository) ensureRoomTurnoverRewardTables(ctx context.Context) error {
	statements := []string{
		`CREATE TABLE IF NOT EXISTS room_turnover_reward_configs (
		  app_code VARCHAR(32) NOT NULL DEFAULT 'lalu' COMMENT '应用编码',
		  region_id BIGINT NOT NULL DEFAULT 0 COMMENT '配置区域 ID；0 表示全区域默认配置',
		  enabled TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否启用',
		  updated_by_admin_id BIGINT NOT NULL DEFAULT 0 COMMENT '最后更新管理员',
		  created_at_ms BIGINT NOT NULL COMMENT '创建时间，UTC epoch ms',
		  updated_at_ms BIGINT NOT NULL COMMENT '更新时间，UTC epoch ms',
		  PRIMARY KEY (app_code, region_id)
		) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='房间流水奖励配置表'`,
		`CREATE TABLE IF NOT EXISTS room_turnover_reward_tiers (
		  tier_id BIGINT NOT NULL AUTO_INCREMENT COMMENT '档位 ID',
		  app_code VARCHAR(32) NOT NULL DEFAULT 'lalu' COMMENT '应用编码',
		  region_id BIGINT NOT NULL DEFAULT 0 COMMENT '配置区域 ID；0 表示全区域默认配置',
		  tier_code VARCHAR(64) NOT NULL COMMENT '档位编码',
		  tier_name VARCHAR(128) NOT NULL COMMENT '档位名称',
		  threshold_coin_spent BIGINT NOT NULL COMMENT '命中该档需要的房间贡献值 HeatValue',
		  reward_coin_amount BIGINT NOT NULL COMMENT '奖励房主金币数',
		  status VARCHAR(32) NOT NULL DEFAULT 'active' COMMENT 'active/inactive',
		  sort_order INT NOT NULL DEFAULT 0 COMMENT '排序',
		  created_at_ms BIGINT NOT NULL COMMENT '创建时间，UTC epoch ms',
		  updated_at_ms BIGINT NOT NULL COMMENT '更新时间，UTC epoch ms',
		  PRIMARY KEY (tier_id),
		  UNIQUE KEY uk_room_turnover_reward_tier_code (app_code, region_id, tier_code),
		  KEY idx_room_turnover_reward_tiers_match (app_code, region_id, status, threshold_coin_spent)
		) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='房间流水奖励档位表'`,
		`CREATE TABLE IF NOT EXISTS room_turnover_reward_event_consumption (
		  app_code VARCHAR(32) NOT NULL DEFAULT 'lalu' COMMENT '应用编码',
		  event_id VARCHAR(128) NOT NULL COMMENT 'room-service outbox event_id',
		  event_type VARCHAR(96) NOT NULL COMMENT '事件类型',
		  room_id VARCHAR(96) NOT NULL COMMENT '房间 ID',
		  period_start_ms BIGINT NOT NULL COMMENT 'UTC 周期开始',
		  coin_spent BIGINT NOT NULL COMMENT '历史字段名：本事件房间贡献值 HeatValue',
		  status VARCHAR(32) NOT NULL COMMENT '消费状态',
		  consumed_at_ms BIGINT NOT NULL COMMENT '消费时间，UTC epoch ms',
		  created_at_ms BIGINT NOT NULL COMMENT '创建时间，UTC epoch ms',
		  updated_at_ms BIGINT NOT NULL COMMENT '更新时间，UTC epoch ms',
		  region_id BIGINT NOT NULL DEFAULT 0 COMMENT '事件发生时房间区域 ID',
		  PRIMARY KEY (app_code, event_id),
		  KEY idx_room_turnover_reward_event_period (app_code, period_start_ms, room_id)
		) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='房间流水奖励事件消费幂等表'`,
		`CREATE TABLE IF NOT EXISTS room_turnover_reward_progress (
		  app_code VARCHAR(32) NOT NULL DEFAULT 'lalu' COMMENT '应用编码',
		  region_id BIGINT NOT NULL DEFAULT 0 COMMENT '事件发生时房间区域 ID；0 表示全区域可见',
		  room_id VARCHAR(96) NOT NULL COMMENT '房间 ID',
		  period_start_ms BIGINT NOT NULL COMMENT 'UTC 周期开始',
		  period_end_ms BIGINT NOT NULL COMMENT 'UTC 周期结束',
		  coin_spent BIGINT NOT NULL DEFAULT 0 COMMENT '历史字段名：本周期房间贡献值 HeatValue',
		  last_event_at_ms BIGINT NOT NULL DEFAULT 0 COMMENT '最后事件时间',
		  created_at_ms BIGINT NOT NULL COMMENT '创建时间，UTC epoch ms',
		  updated_at_ms BIGINT NOT NULL COMMENT '更新时间，UTC epoch ms',
		  PRIMARY KEY (app_code, region_id, room_id, period_start_ms),
		  KEY idx_room_turnover_reward_progress_period (app_code, period_start_ms, coin_spent)
		) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='房间流水奖励周期聚合表'`,
		`CREATE TABLE IF NOT EXISTS room_turnover_reward_settlements (
		  app_code VARCHAR(32) NOT NULL DEFAULT 'lalu' COMMENT '应用编码',
		  region_id BIGINT NOT NULL DEFAULT 0 COMMENT '结算对应房间区域 ID；0 表示全区域可见',
		  settlement_id VARCHAR(96) NOT NULL COMMENT '结算 ID',
		  room_id VARCHAR(96) NOT NULL COMMENT '房间 ID',
		  owner_user_id BIGINT NOT NULL DEFAULT 0 COMMENT '结算收款房主',
		  period_start_ms BIGINT NOT NULL COMMENT 'UTC 周期开始',
		  period_end_ms BIGINT NOT NULL COMMENT 'UTC 周期结束',
		  coin_spent BIGINT NOT NULL DEFAULT 0 COMMENT '历史字段名：周期房间贡献值 HeatValue',
		  tier_id BIGINT NOT NULL DEFAULT 0 COMMENT '命中档位 ID',
		  tier_code VARCHAR(64) NOT NULL DEFAULT '' COMMENT '命中档位编码',
		  threshold_coin_spent BIGINT NOT NULL DEFAULT 0 COMMENT '命中档位阈值',
		  reward_coin_amount BIGINT NOT NULL DEFAULT 0 COMMENT '发放金币',
		  status VARCHAR(32) NOT NULL DEFAULT 'pending' COMMENT 'pending/granted/failed',
		  wallet_command_id VARCHAR(160) NOT NULL DEFAULT '' COMMENT 'wallet-service 幂等命令 ID',
		  wallet_transaction_id VARCHAR(128) NOT NULL DEFAULT '' COMMENT '钱包交易 ID',
		  failure_reason VARCHAR(512) NOT NULL DEFAULT '' COMMENT '失败原因',
		  settled_at_ms BIGINT NOT NULL DEFAULT 0 COMMENT '成功发放时间',
		  created_at_ms BIGINT NOT NULL COMMENT '创建时间，UTC epoch ms',
		  updated_at_ms BIGINT NOT NULL COMMENT '更新时间，UTC epoch ms',
		  PRIMARY KEY (app_code, settlement_id),
		  UNIQUE KEY uk_room_turnover_reward_settlement_room_period (app_code, region_id, room_id, period_start_ms),
		  KEY idx_room_turnover_reward_settlement_region (app_code, region_id, period_start_ms, created_at_ms),
		  KEY idx_room_turnover_reward_settlement_status (app_code, status, period_start_ms, created_at_ms),
		  KEY idx_room_turnover_reward_settlement_owner (app_code, owner_user_id, period_start_ms)
		) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='房间流水奖励每周结算表'`,
	}
	for _, statement := range statements {
		if _, err := r.db.ExecContext(ctx, statement); err != nil {
			return err
		}
	}
	return r.ensureRoomTurnoverRewardRegionSchema(ctx)
}

func (r *Repository) ensureRoomTurnoverRewardRegionSchema(ctx context.Context) error {
	// 本地旧库的全 App 配置回填为 0 后继续作为全区域默认配置，避免区域能力上线时中断原有奖励。
	additions := []struct {
		table     string
		statement string
	}{
		{"room_turnover_reward_configs", `ALTER TABLE room_turnover_reward_configs ADD COLUMN region_id BIGINT NOT NULL DEFAULT 0 COMMENT '配置区域 ID；0 表示全区域默认配置', ALGORITHM=INSTANT`},
		{"room_turnover_reward_tiers", `ALTER TABLE room_turnover_reward_tiers ADD COLUMN region_id BIGINT NOT NULL DEFAULT 0 COMMENT '配置区域 ID；0 表示全区域默认配置', ALGORITHM=INSTANT`},
		{"room_turnover_reward_event_consumption", `ALTER TABLE room_turnover_reward_event_consumption ADD COLUMN region_id BIGINT NOT NULL DEFAULT 0 COMMENT '事件发生时房间区域 ID', ALGORITHM=INSTANT`},
		{"room_turnover_reward_progress", `ALTER TABLE room_turnover_reward_progress ADD COLUMN region_id BIGINT NOT NULL DEFAULT 0 COMMENT '事件发生时房间区域 ID', ALGORITHM=INSTANT`},
		{"room_turnover_reward_settlements", `ALTER TABLE room_turnover_reward_settlements ADD COLUMN region_id BIGINT NOT NULL DEFAULT 0 COMMENT '结算对应房间区域 ID', ALGORITHM=INSTANT`},
	}
	for _, addition := range additions {
		exists, err := r.columnExists(ctx, addition.table, "region_id")
		if err != nil {
			return err
		}
		if !exists {
			if _, err := r.db.ExecContext(ctx, addition.statement); err != nil {
				return err
			}
		}
	}

	// 配置和流水业务键都必须包含 region_id。单条 ALTER 合并索引重建，避免本地旧库为同一张表重复扫描。
	indexMigrations := []struct {
		table     string
		index     string
		columns   []string
		statement string
	}{
		{"room_turnover_reward_configs", "PRIMARY", []string{"app_code", "region_id"}, `ALTER TABLE room_turnover_reward_configs DROP PRIMARY KEY, ADD PRIMARY KEY (app_code, region_id), ALGORITHM=INPLACE, LOCK=NONE`},
		{"room_turnover_reward_tiers", "uk_room_turnover_reward_tier_code", []string{"app_code", "region_id", "tier_code"}, `ALTER TABLE room_turnover_reward_tiers DROP INDEX uk_room_turnover_reward_tier_code, ADD UNIQUE KEY uk_room_turnover_reward_tier_code (app_code, region_id, tier_code), ALGORITHM=INPLACE, LOCK=NONE`},
		{"room_turnover_reward_tiers", "idx_room_turnover_reward_tiers_match", []string{"app_code", "region_id", "status", "threshold_coin_spent"}, `ALTER TABLE room_turnover_reward_tiers DROP INDEX idx_room_turnover_reward_tiers_match, ADD KEY idx_room_turnover_reward_tiers_match (app_code, region_id, status, threshold_coin_spent), ALGORITHM=INPLACE, LOCK=NONE`},
		{"room_turnover_reward_progress", "PRIMARY", []string{"app_code", "region_id", "room_id", "period_start_ms"}, `ALTER TABLE room_turnover_reward_progress DROP PRIMARY KEY, ADD PRIMARY KEY (app_code, region_id, room_id, period_start_ms), ALGORITHM=INPLACE, LOCK=NONE`},
		{"room_turnover_reward_settlements", "uk_room_turnover_reward_settlement_room_period", []string{"app_code", "region_id", "room_id", "period_start_ms"}, `ALTER TABLE room_turnover_reward_settlements DROP INDEX uk_room_turnover_reward_settlement_room_period, ADD UNIQUE KEY uk_room_turnover_reward_settlement_room_period (app_code, region_id, room_id, period_start_ms), ALGORITHM=INPLACE, LOCK=NONE`},
	}
	for _, migration := range indexMigrations {
		matches, err := r.indexColumnsMatch(ctx, migration.table, migration.index, migration.columns)
		if err != nil {
			return err
		}
		if !matches {
			if _, err := r.db.ExecContext(ctx, migration.statement); err != nil {
				return err
			}
		}
	}
	regionIndexExists, err := r.indexExists(ctx, "room_turnover_reward_settlements", "idx_room_turnover_reward_settlement_region")
	if err != nil {
		return err
	}
	if !regionIndexExists {
		// 后台按区域分页时直接走 app_code + region_id 的有序索引，避免区域配置上线后退化成结算全表扫描。
		if _, err := r.db.ExecContext(ctx, `ALTER TABLE room_turnover_reward_settlements ADD KEY idx_room_turnover_reward_settlement_region (app_code, region_id, period_start_ms, created_at_ms), ALGORITHM=INPLACE, LOCK=NONE`); err != nil {
			return err
		}
	}
	return nil
}
