<?php
/**
 * 渠道扁平化迁移脚本（多级子渠道用户归并到顶级渠道后删除子渠道）
 * 用法：在 server 目录下执行 php db/run_dept_flatten_channels.php
 */
require_once __DIR__ . '/../vendor/autoload.php';

use plugin\saiadmin\app\model\system\SystemDept;
use plugin\saiadmin\app\model\system\SystemUser;
use support\think\Db;

$bootstrap = __DIR__ . '/../support/bootstrap.php';
if (is_file($bootstrap)) {
    require_once $bootstrap;
}

function getRootDeptId(int $deptId): ?int
{
    $currentId = $deptId;
    $visited = [];
    while ($currentId > 0 && !isset($visited[$currentId])) {
        $visited[$currentId] = true;
        $dept = SystemDept::find($currentId);
        if (!$dept) {
            return null;
        }
        $parentId = (int) ($dept->parent_id ?? 0);
        if ($parentId === 0) {
            return $currentId;
        }
        $currentId = $parentId;
    }
    return $currentId > 0 ? $currentId : null;
}

Db::transaction(function () {
    $users = SystemUser::where('dept_id', '>', 0)->select();
    foreach ($users as $user) {
        $deptId = (int) $user->dept_id;
        $rootId = getRootDeptId($deptId);
        if ($rootId !== null && $rootId !== $deptId) {
            SystemUser::where('id', $user->id)->update(['dept_id' => $rootId]);
            echo "用户 {$user->id} dept_id {$deptId} -> {$rootId}\n";
        }
    }

    $childIds = SystemDept::where('parent_id', '>', 0)->column('id');
    if (!empty($childIds)) {
        SystemDept::destroy($childIds);
        echo '已删除子渠道: ' . implode(',', $childIds) . "\n";
    }

    SystemDept::where('id', '>', 0)->update(['parent_id' => 0, 'level' => '0']);
    echo "渠道扁平化完成\n";
});
