<?php
/** 仅新增聊天室表；默认预览，--apply 执行。 */
function chatSchema($prefix) {
    if (!preg_match('/^[a-zA-Z0-9_]*$/', $prefix)) throw new RuntimeException('Invalid prefix');
    $tables = [
        'chat_room' => "id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, title VARCHAR(120) NOT NULL, category VARCHAR(16) NOT NULL, visibility VARCHAR(16) NOT NULL, description TEXT NOT NULL, owner_id INT UNSIGNED NOT NULL, client_id VARCHAR(80) NOT NULL, status VARCHAR(16) NOT NULL DEFAULT 'open', expires_at BIGINT UNSIGNED NULL, closed_at BIGINT UNSIGNED NULL, reminder_stage TINYINT NOT NULL DEFAULT 0, version BIGINT UNSIGNED NOT NULL DEFAULT 0, member_count INT UNSIGNED NOT NULL DEFAULT 0, created_at BIGINT UNSIGNED NOT NULL, PRIMARY KEY(id), UNIQUE KEY owner_request(owner_id,client_id), KEY expiry(status,expires_at), KEY public_list(visibility,status,id)",
        'chat_member' => "room_id BIGINT UNSIGNED NOT NULL, user_id INT UNSIGNED NOT NULL, status VARCHAR(16) NOT NULL, muted TINYINT NOT NULL DEFAULT 0, last_read BIGINT UNSIGNED NOT NULL DEFAULT 0, last_mention BIGINT UNSIGNED NOT NULL DEFAULT 0, attention TINYINT NOT NULL DEFAULT 0, joined_at BIGINT UNSIGNED NOT NULL, PRIMARY KEY(room_id,user_id), KEY user_rooms(user_id,status,room_id)",
        'chat_message' => "id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, room_id BIGINT UNSIGNED NOT NULL, sender_id INT UNSIGNED NOT NULL, sender_name VARCHAR(120) NOT NULL, client_id VARCHAR(80) NOT NULL, type VARCHAR(16) NOT NULL, content TEXT NOT NULL, image_id VARCHAR(64) NULL, reply_id BIGINT UNSIGNED NULL, mentions TEXT NOT NULL, recalled TINYINT NOT NULL DEFAULT 0, revision BIGINT UNSIGNED NOT NULL, created_at BIGINT UNSIGNED NOT NULL, PRIMARY KEY(id), UNIQUE KEY sender_request(room_id,sender_id,client_id), KEY room_history(room_id,id), KEY room_changes(room_id,revision)",
        'chat_invite' => "token_hash CHAR(64) NOT NULL, room_id BIGINT UNSIGNED NOT NULL, owner_id INT UNSIGNED NOT NULL, expires_at BIGINT UNSIGNED NOT NULL, PRIMARY KEY(token_hash), KEY room_invites(room_id)",
        'chat_image' => "id CHAR(64) NOT NULL, room_id BIGINT UNSIGNED NOT NULL, user_id INT UNSIGNED NOT NULL, path VARCHAR(255) NOT NULL, created_at BIGINT UNSIGNED NOT NULL, PRIMARY KEY(id), KEY room_images(room_id)",
        'chat_report' => "id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, room_id BIGINT UNSIGNED NOT NULL, message_id BIGINT UNSIGNED NOT NULL, user_id INT UNSIGNED NOT NULL, reason VARCHAR(1200) NOT NULL, status VARCHAR(16) NOT NULL DEFAULT 'pending', created_at BIGINT UNSIGNED NOT NULL, PRIMARY KEY(id), UNIQUE KEY reporter_message(user_id,message_id), KEY pending_reports(status,id)",
        'chat_log' => "id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, room_id BIGINT UNSIGNED NOT NULL, user_id INT UNSIGNED NOT NULL, action VARCHAR(32) NOT NULL, detail VARCHAR(1200) NOT NULL, created_at BIGINT UNSIGNED NOT NULL, PRIMARY KEY(id), KEY room_logs(room_id,id)"
    ];
    $sql = [];
    foreach ($tables as $table => $columns) $sql[] = "CREATE TABLE IF NOT EXISTS `{$prefix}{$table}` ($columns) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";
    return $sql;
}
if (PHP_SAPI !== 'cli' || realpath($_SERVER['SCRIPT_FILENAME'] ?? '') !== __FILE__) return;
require dirname(__DIR__).'/vendor/autoload.php';
$app = new \think\App(dirname(__DIR__).'/'); $app->initialize();
$connection = $app->config->get('database.connections.'.$app->config->get('database.default'));
$sql = chatSchema($connection['prefix']);
$apply = in_array('--apply', $argv, true);
if ($apply) {
    foreach ($sql as $statement) \think\facade\Db::execute($statement);
    if (!\think\facade\Db::query("SHOW COLUMNS FROM `{$connection['prefix']}chat_room` LIKE 'reminder_stage'")) \think\facade\Db::execute("ALTER TABLE `{$connection['prefix']}chat_room` ADD reminder_stage TINYINT NOT NULL DEFAULT 0");
    if (!\think\facade\Db::query("SHOW COLUMNS FROM `{$connection['prefix']}chat_member` LIKE 'last_mention'")) \think\facade\Db::execute("ALTER TABLE `{$connection['prefix']}chat_member` ADD last_mention BIGINT UNSIGNED NOT NULL DEFAULT 0");
    if (!\think\facade\Db::name('chat_room')->find(1)) \think\facade\Db::name('chat_room')->insert(['id'=>1,'title'=>'公共大厅','category'=>'其他','visibility'=>'public','description'=>'欢迎来到维智捷聊天室。二手转让、假期出游、日常答疑，都可以在这里交流。请尊重同事，文明发言。','owner_id'=>0,'client_id'=>'hall','status'=>'open','expires_at'=>null,'created_at'=>(int)(microtime(true)*1000)]);
}
echo json_encode(['applied'=>$apply,'tables'=>count($sql),'sql'=>$apply ? [] : $sql], JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT), PHP_EOL;
