<?php
/**
 * 执行 sa_system_role 渠道隔离迁移，并为已有渠道复制默认角色、映射用户角色
 *
 * 用法（在 server 目录）: php db/run_sa_system_role_dept_id.php
 */
declare(strict_types=1);

require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../support/bootstrap.php';

use plugin\saiadmin\app\service\SystemRoleChannelService;
use support\think\Db;

function tableHasColumn(string $table, string $column): bool
{
    try {
        $fields = Db::getFields($table);
        return isset($fields[$column]);
    } catch (\Throwable $e) {
        return false;
    }
}

function indexExists(string $table, string $indexName): bool
{
    $rows = Db::query("SHOW INDEX FROM `{$table}` WHERE Key_name = ?", [$indexName]);
    return !empty($rows);
}

echo "=== sa_system_role dept_id migration ===\n";

if (!tableHasColumn('sa_system_role', 'dept_id')) {
    Db::execute(
        "ALTER TABLE `sa_system_role`
         ADD COLUMN `dept_id` bigint(20) UNSIGNED NOT NULL DEFAULT 0 COMMENT '所属渠道ID，0=默认模板' AFTER `id`"
    );
    echo "OK: ADD COLUMN dept_id\n";
} else {
    echo "SKIP: dept_id column exists\n";
}

if (!indexExists('sa_system_role', 'idx_dept_id')) {
    Db::execute('ALTER TABLE `sa_system_role` ADD INDEX `idx_dept_id` (`dept_id`)');
    echo "OK: ADD INDEX idx_dept_id\n";
} else {
    echo "SKIP: idx_dept_id exists\n";
}

Db::execute('UPDATE `sa_system_role` SET `dept_id` = 0 WHERE `id` > 1');
echo "OK: UPDATE template dept_id\n";

if (indexExists('sa_system_role', 'uk_slug')) {
    Db::execute('ALTER TABLE `sa_system_role` DROP INDEX `uk_slug`');
    echo "OK: DROP INDEX uk_slug\n";
} else {
    echo "SKIP: uk_slug not found\n";
}

if (!indexExists('sa_system_role', 'uk_dept_code')) {
    Db::execute('ALTER TABLE `sa_system_role` ADD UNIQUE KEY `uk_dept_code` (`dept_id`, `code`)');
    echo "OK: ADD UNIQUE uk_dept_code\n";
} else {
    echo "SKIP: uk_dept_code exists\n";
}

$service = new SystemRoleChannelService();
$sync = $service->syncAllChannelsFromDefault();
echo "Synced roles for channels: " . json_encode($sync, JSON_UNESCAPED_UNICODE) . "\n";

$mapped = $service->remapUserRolesToChannelRoles();
echo "Remapped user roles: {$mapped}\n";

echo "Done.\n";
