<?php
/** CLI: 默认预览；--apply 执行。使用环境的 TP6 默认连接，不同步 .env。 */
function suggestionTransferSchema($prefix) {
    if (!preg_match('/^[a-zA-Z0-9_]*$/D', $prefix)) throw new RuntimeException('Invalid prefix');
    return "CREATE TABLE IF NOT EXISTS `{$prefix}onsite_suggestion_transfer` (
        id INT UNSIGNED NOT NULL AUTO_INCREMENT, suggestion_id INT UNSIGNED NOT NULL,
        from_owner INT UNSIGNED NOT NULL, to_owner INT UNSIGNED NOT NULL,
        from_name VARCHAR(100) NOT NULL, to_name VARCHAR(100) NOT NULL,
        from_department VARCHAR(100) NOT NULL, to_department VARCHAR(100) NOT NULL,
        reason TEXT NOT NULL, reply TEXT NOT NULL,
        state VARCHAR(16) NOT NULL DEFAULT 'pending',
        actor_id INT UNSIGNED NOT NULL DEFAULT 0,
        created_at INT UNSIGNED NOT NULL, handled_at INT UNSIGNED NOT NULL DEFAULT 0,
        PRIMARY KEY(id), KEY suggestion_history(suggestion_id,id), KEY recipient(to_owner,state,id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='合理化建议负责人转移申请和历史'";
}
if (PHP_SAPI !== 'cli' || realpath($_SERVER['SCRIPT_FILENAME'] ?? '') !== __FILE__) return;
require dirname(__DIR__).'/vendor/autoload.php';
$app = new \think\App(dirname(__DIR__).'/'); $app->initialize();
$config = config('database.connections.'.config('database.default'));
$prefix = $config['prefix'];
$sql = [suggestionTransferSchema($prefix)];
$table = $prefix.'onsite_suggestion_list';
$info = \think\facade\Db::query('SHOW TABLE STATUS WHERE Name = ?', [$table]);
if (!$info) throw new RuntimeException('Suggestion table missing');
// 保留建议原表的存储引擎；业务写入使用短时表锁保护 MyISAM。
$fields = array_column(\think\facade\Db::query("SHOW COLUMNS FROM `{$table}`"), 'Field');
if (!in_array('transfer_id', $fields, true)) $sql[] = "ALTER TABLE `{$table}` ADD transfer_id INT UNSIGNED NOT NULL DEFAULT 0";
if (!in_array('transfer_to', $fields, true)) $sql[] = "ALTER TABLE `{$table}` ADD transfer_to INT UNSIGNED NOT NULL DEFAULT 0, ADD INDEX pending_transfer_recipient(transfer_to,transfer_id)";
else {
    $indexes=array_column(\think\facade\Db::query("SHOW INDEX FROM `{$table}`"),'Key_name');
    if(!in_array('pending_transfer_recipient',$indexes,true))$sql[]="ALTER TABLE `{$table}` ADD INDEX pending_transfer_recipient(transfer_to,transfer_id)";
}
$transferTable=$prefix.'onsite_suggestion_transfer';
$transferInfo=\think\facade\Db::query('SHOW TABLE STATUS WHERE Name = ?',[$transferTable]);
if($transferInfo){
    $actual=array_column(\think\facade\Db::query("SHOW COLUMNS FROM `{$transferTable}`"),'Field');
    $required=['id','suggestion_id','from_owner','to_owner','from_name','to_name','from_department','to_department','reason','reply','state','actor_id','created_at','handled_at'];
    $missing=array_diff($required,$actual);
    if($missing)throw new RuntimeException('Transfer table missing columns: '.implode(', ',$missing));
    if(strtolower($transferInfo[0]['Engine'])!=='innodb')$sql[]="ALTER TABLE `{$transferTable}` ENGINE=InnoDB";
}
$apply = in_array('--apply', $argv, true);
if ($apply) {
    foreach ($sql as $statement) \think\facade\Db::execute($statement);
    // 删除本表旧字段缓存，让新字段即时可写。
    $cache = $app->getRuntimePath().'schema/'.$config['database'].'.'.$table.'.php';
    if (is_file($cache)) unlink($cache);
}
echo json_encode(['database'=>$config['database'],'applied'=>$apply,'suggestionEnginePreserved'=>$info[0]['Engine'],'sql'=>$sql], JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT), PHP_EOL;
