use rusqlite::Connection;
use std::sync::Mutex;

pub struct MarkBaseVolume {
    sqlite: Mutex<Connection>,
    user_id: String,
    root_id: String,
}

impl MarkBaseVolume {
    pub fn new(conn: Connection, user_id: String) -> Self {
        let root_id = Self::find_root_node(&conn, &user_id);
        
        Self {
            sqlite: Mutex::new(conn),
            user_id,
            root_id,
        }
    }
    
    fn find_root_node(conn: &Connection, user_id: &str) -> String {
        conn.query_row(
            "SELECT node_id FROM file_nodes 
             WHERE parent_id IS NULL 
             LIMIT 1",
            [],
            |row| row.get::<_, String>(0),
        ).unwrap_or_else(|_| "root".to_string())
    }
    
    pub fn get_root_id(&self) -> &str {
        &self.root_id
    }
    
    pub fn get_user_id(&self) -> &str {
        &self.user_id
    }
    
    pub fn statfs(&self) -> (i64, i64) {
        let conn = self.sqlite.lock().unwrap();
        
        let total_nodes: i64 = conn.query_row(
            "SELECT COUNT(*) FROM file_nodes",
            [],
            |row| row.get(0),
        ).unwrap_or(0);
        
        let total_size: i64 = conn.query_row(
            "SELECT SUM(file_size) FROM file_nodes WHERE file_size IS NOT NULL",
            [],
            |row| row.get(0),
        ).unwrap_or(0);
        
        (total_nodes, total_size)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    
    #[test]
    fn test_volume_creation() {
        let conn = Connection::open("data/users/test.sqlite").unwrap();
        let vol = MarkBaseVolume::new(conn, "test".to_string());
        assert_eq!(vol.get_user_id(), "test");
    }
}