<?php
/**
 * 仅执行渠道配置同步（步骤 4-6），适用于已完成表结构迁移后
 * 用法：php db/run_sync_channel_config.php
 */
declare(strict_types=1);

define('BASE_PATH', dirname(__DIR__));
require_once BASE_PATH . '/vendor/autoload.php';

if (class_exists(\Dotenv\Dotenv::class) && is_file(BASE_PATH . '/.env')) {
    \Dotenv\Dotenv::createUnsafeMutable(BASE_PATH)->load();
}
\Webman\Config::load(BASE_PATH . '/config', ['route', 'plugin']);
\Webman\ThinkOrm\ThinkOrm::start(null);

use app\dice\service\DiceChannelConfigService;
use plugin\saiadmin\app\model\system\SystemDept;
use support\think\Db;

echo "========== 渠道配置同步 ==========\n";

$service = new DiceChannelConfigService();
echo "调整配置表主键与默认模板 dept_id=0...\n";
$service->ensureConfigCompositeKeys();

$tables = ['dice_config', 'dice_ante_config', 'dice_lottery_pool_config', 'dice_reward_config', 'dice_reward', 'dice_game'];

echo "\n清理各渠道不完整配置后重新复制...\n";
$deptIds = SystemDept::column('id');
foreach ($deptIds as $deptId) {
    $deptId = (int) $deptId;
    if ($deptId <= 0) {
        continue;
    }
    foreach ($tables as $table) {
        try {
            Db::table($table)->where('dept_id', $deptId)->delete();
        } catch (\Throwable $e) {
        }
    }
}

echo "设为默认模板 (dept_id=0)...\n";
foreach ($tables as $table) {
    Db::table($table)->whereNull('dept_id')->update(['dept_id' => 0]);
}

echo "从默认模板复制到各渠道...\n";
$summary = $service->syncAllChannelsFromDefault();
foreach ($summary as $deptId => $info) {
    echo "渠道 {$deptId}: 复制 [" . (implode(',', $info['copied'] ?? []) ?: '无') . "] 跳过 [" . (implode(',', $info['skipped'] ?? []) ?: '无') . "]\n";
}

echo "\n回填 dept_id...\n";
print_r($service->backfillDataDeptId());

echo "\n渠道数: " . SystemDept::count() . "\n完成。\n";
