//! 数据库表结构定义

use rusqlite::Connection;
use crate::utils::AppError;

/// 初始化数据库表结构
pub fn init_database(conn: &Connection) -> Result<(), AppError> {
    // 创建聊天消息表
    conn.execute(
        r#"
        CREATE TABLE IF NOT EXISTS chat_messages (
            id TEXT PRIMARY KEY,
            message_type TEXT NOT NULL,
            content TEXT NOT NULL,
            from_device TEXT NOT NULL,
            to_device TEXT NOT NULL,
            timestamp INTEGER NOT NULL,
            status TEXT NOT NULL DEFAULT 'pending',
            created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now'))
        )
        "#,
        [],
    )?;

    // 创建聊天消息索引
    conn.execute(
        r#"
        CREATE INDEX IF NOT EXISTS idx_messages_devices 
        ON chat_messages(from_device, to_device)
        "#,
        [],
    )?;

    conn.execute(
        r#"
        CREATE INDEX IF NOT EXISTS idx_messages_timestamp 
        ON chat_messages(timestamp DESC)
        "#,
        [],
    )?;

    // 创建文件传输记录表
    conn.execute(
        r#"
        CREATE TABLE IF NOT EXISTS file_transfers (
            file_id TEXT PRIMARY KEY,
            name TEXT NOT NULL,
            size INTEGER NOT NULL,
            progress REAL NOT NULL DEFAULT 0.0,
            status TEXT NOT NULL DEFAULT 'pending',
            mime_type TEXT NOT NULL,
            from_device TEXT NOT NULL,
            to_device TEXT NOT NULL,
            local_path TEXT,
            created_at INTEGER NOT NULL,
            completed_at INTEGER,
            transferred_bytes INTEGER NOT NULL DEFAULT 0
        )
        "#,
        [],
    )?;

    // 迁移：为旧表添加 transferred_bytes 字段（如果不存在）
    let _ = conn.execute(
        "ALTER TABLE file_transfers ADD COLUMN transferred_bytes INTEGER NOT NULL DEFAULT 0",
        [],
    );

    // 创建文件传输索引
    conn.execute(
        r#"
        CREATE INDEX IF NOT EXISTS idx_transfers_devices 
        ON file_transfers(from_device, to_device)
        "#,
        [],
    )?;

    conn.execute(
        r#"
        CREATE INDEX IF NOT EXISTS idx_transfers_status 
        ON file_transfers(status)
        "#,
        [],
    )?;

    // 创建设备信息表 (用于持久化已知设备)
    conn.execute(
        r#"
        CREATE TABLE IF NOT EXISTS known_devices (
            device_id TEXT PRIMARY KEY,
            device_name TEXT NOT NULL,
            ip TEXT NOT NULL,
            ws_port INTEGER NOT NULL,
            http_port INTEGER NOT NULL,
            last_seen INTEGER NOT NULL,
            created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now'))
        )
        "#,
        [],
    )?;

    // 创建应用配置表
    conn.execute(
        r#"
        CREATE TABLE IF NOT EXISTS app_config (
            key TEXT PRIMARY KEY,
            value TEXT NOT NULL
        )
        "#,
        [],
    )?;

    log::info!("Database schema initialized successfully");
    Ok(())
}
