<?php
/** CLI：只新增一张站内消息表；默认预览，--apply 执行。 */
function messageSchema($prefix) {
    if (!preg_match('/^[a-zA-Z0-9_]*$/', $prefix)) throw new RuntimeException('Invalid prefix');
    return "CREATE TABLE IF NOT EXISTS `{$prefix}message` (
        id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
        auth_id INT UNSIGNED NOT NULL,
        business VARCHAR(32) NOT NULL, business_id BIGINT UNSIGNED NOT NULL,
        node VARCHAR(80) NOT NULL,
        state VARCHAR(16) NOT NULL COMMENT 'pending/done/closed/notice',
        title VARCHAR(120) NOT NULL, stage VARCHAR(80) NOT NULL,
        fields TEXT NOT NULL, route VARCHAR(255) NOT NULL,
        task_at INT UNSIGNED NOT NULL DEFAULT 0, deadline INT UNSIGNED NOT NULL DEFAULT 0,
        read_at INT UNSIGNED NOT NULL DEFAULT 0, handled_at INT UNSIGNED NOT NULL DEFAULT 0,
        created_at INT UNSIGNED NOT NULL, updated_at INT UNSIGNED NOT NULL,
        PRIMARY KEY(id), UNIQUE KEY recipient_node(auth_id,business,business_id,node),
        KEY recipient_list(auth_id,state,task_at,id), KEY recipient_unread(auth_id,state,read_at)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='统一站内待办及通知；业务表决定处理权限'";
}
if (PHP_SAPI !== 'cli' || realpath($_SERVER['SCRIPT_FILENAME'] ?? '') !== __FILE__) return;
$root = $argv[1] ?? 'D:/phpstudy_pro/WWW/cqoms.com';
if ($root === '--apply') $root = 'D:/phpstudy_pro/WWW/cqoms.com';
require $root.'/vendor/autoload.php';
$app = new \think\App(rtrim($root, '/\\').'/'); $app->initialize();
$connection = $app->config->get('database.connections.'.$app->config->get('database.default'));
$sql = messageSchema($connection['prefix']); $apply = in_array('--apply', $argv, true);
if ($apply) \think\facade\Db::execute($sql);
echo json_encode(['database'=>$connection['database'],'applied'=>$apply,'sql'=>$sql], JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT), PHP_EOL;
