-- FunMC 客户端本地数据库
-- 用于存储本地缓存和设置

-- 用户会话信息缓存
CREATE TABLE IF NOT EXISTS user_session (
    id INTEGER PRIMARY KEY CHECK (id = 1),
    user_id TEXT NOT NULL,
    username TEXT NOT NULL,
    email TEXT NOT NULL,
    avatar_seed TEXT NOT NULL,
    access_token TEXT NOT NULL,
    refresh_token TEXT NOT NULL,
    server_url TEXT NOT NULL DEFAULT 'https://funmc.com',
    created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now'))
);

-- 最近加入的房间缓存
CREATE TABLE IF NOT EXISTS recent_rooms (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    room_id TEXT NOT NULL UNIQUE,
    room_name TEXT NOT NULL,
    owner_username TEXT NOT NULL,
    game_version TEXT NOT NULL DEFAULT '1.20',
    last_joined_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now'))
);

-- 好友缓存（用于离线显示）
CREATE TABLE IF NOT EXISTS friends_cache (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id TEXT NOT NULL UNIQUE,
    username TEXT NOT NULL,
    avatar_seed TEXT NOT NULL,
    is_online INTEGER NOT NULL DEFAULT 0,
    cached_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now'))
);

-- 应用设置
CREATE TABLE IF NOT EXISTS app_settings (
    key TEXT PRIMARY KEY NOT NULL,
    value TEXT NOT NULL,
    updated_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now'))
);

-- 连接历史记录
CREATE TABLE IF NOT EXISTS connection_history (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    room_id TEXT NOT NULL,
    room_name TEXT NOT NULL,
    session_type TEXT NOT NULL CHECK (session_type IN ('p2p', 'relay')),
    local_port INTEGER NOT NULL,
    bytes_sent INTEGER NOT NULL DEFAULT 0,
    bytes_received INTEGER NOT NULL DEFAULT 0,
    latency_ms INTEGER,
    started_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')),
    ended_at INTEGER
);

-- 中继节点延迟缓存
CREATE TABLE IF NOT EXISTS relay_latency_cache (
    node_url TEXT PRIMARY KEY NOT NULL,
    node_name TEXT NOT NULL,
    latency_ms INTEGER NOT NULL,
    tested_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now'))
);

-- 索引
CREATE INDEX IF NOT EXISTS idx_recent_rooms_last_joined ON recent_rooms(last_joined_at DESC);
CREATE INDEX IF NOT EXISTS idx_connection_history_started ON connection_history(started_at DESC);
