//! 数据库管理

use anyhow::Result;
use sqlx::{sqlite::SqlitePoolOptions, Pool, Sqlite};

pub type DbPool = Pool<Sqlite>;

#[derive(Clone)]
pub struct Database {
    pub pool: DbPool,
}

impl Database {
    pub async fn new(database_url: &str) -> Result<Self> {
        let pool = SqlitePoolOptions::new()
            .max_connections(10)
            .connect(database_url)
            .await?;

        Ok(Self { pool })
    }

    pub async fn migrate(&self) -> Result<()> {
        // 创建用户表
        sqlx::query(
            r#"
            CREATE TABLE IF NOT EXISTS users (
                id TEXT PRIMARY KEY,
                username TEXT UNIQUE NOT NULL,
                password_hash TEXT NOT NULL,
                salt TEXT NOT NULL,
                email TEXT,
                role TEXT NOT NULL DEFAULT 'user',
                created_at TEXT NOT NULL,
                last_login TEXT
            )
            "#,
        )
        .execute(&self.pool)
        .await?;

        // 创建设备表
        sqlx::query(
            r#"
            CREATE TABLE IF NOT EXISTS devices (
                id TEXT PRIMARY KEY,
                device_id TEXT UNIQUE NOT NULL,
                name TEXT NOT NULL,
                os_type TEXT NOT NULL,
                os_version TEXT NOT NULL,
                user_id TEXT,
                is_online INTEGER NOT NULL DEFAULT 0,
                allow_remote INTEGER NOT NULL DEFAULT 0,
                verification_code TEXT,
                last_seen TEXT NOT NULL,
                created_at TEXT NOT NULL,
                FOREIGN KEY (user_id) REFERENCES users(id)
            )
            "#,
        )
        .execute(&self.pool)
        .await?;

        // 创建会话表
        sqlx::query(
            r#"
            CREATE TABLE IF NOT EXISTS sessions (
                id TEXT PRIMARY KEY,
                controller_device_id TEXT NOT NULL,
                controlled_device_id TEXT NOT NULL,
                started_at TEXT NOT NULL,
                ended_at TEXT,
                connection_type TEXT NOT NULL,
                status TEXT NOT NULL,
                FOREIGN KEY (controller_device_id) REFERENCES devices(device_id),
                FOREIGN KEY (controlled_device_id) REFERENCES devices(device_id)
            )
            "#,
        )
        .execute(&self.pool)
        .await?;

        // 创建控制历史表
        sqlx::query(
            r#"
            CREATE TABLE IF NOT EXISTS control_history (
                id TEXT PRIMARY KEY,
                user_id TEXT,
                controller_device_id TEXT NOT NULL,
                controlled_device_id TEXT NOT NULL,
                controlled_device_name TEXT NOT NULL,
                started_at TEXT NOT NULL,
                ended_at TEXT,
                duration_seconds INTEGER,
                connection_type TEXT NOT NULL,
                FOREIGN KEY (user_id) REFERENCES users(id)
            )
            "#,
        )
        .execute(&self.pool)
        .await?;

        // 创建索引
        sqlx::query("CREATE INDEX IF NOT EXISTS idx_devices_user_id ON devices(user_id)")
            .execute(&self.pool)
            .await?;
        sqlx::query("CREATE INDEX IF NOT EXISTS idx_devices_device_id ON devices(device_id)")
            .execute(&self.pool)
            .await?;
        sqlx::query("CREATE INDEX IF NOT EXISTS idx_sessions_controller ON sessions(controller_device_id)")
            .execute(&self.pool)
            .await?;
        sqlx::query("CREATE INDEX IF NOT EXISTS idx_history_user_id ON control_history(user_id)")
            .execute(&self.pool)
            .await?;

        tracing::info!("Database migrations completed");
        Ok(())
    }
}
