//! Storage Manager Tests - TDD Approach

use geographdb_core::storage::data_structures::NodeRec;
use geographdb_core::storage::manager::StorageManager;

#[test]
fn test_storage_manager_create() {
    let temp_dir = tempfile::tempdir().unwrap();
    let db_path = temp_dir.path().join("test.db");

    let result = StorageManager::create(&db_path);

    assert!(result.is_ok(), "Should create storage manager");
}

#[test]
fn test_storage_manager_insert_node() {
    let temp_dir = tempfile::tempdir().unwrap();
    let db_path = temp_dir.path().join("test.db");
    let mut storage = StorageManager::create(&db_path).unwrap();

    let node = NodeRec {
        id: 1,
        morton_code: 0,
        x: 10.0,
        y: 20.0,
        z: 30.0,
        edge_off: 0,
        edge_len: 0,
        flags: 0,
        begin_ts: 0,
        end_ts: 0,
        tx_id: 0,
        visibility: 1,
        _padding: [0; 7],
    };

    let result = storage.insert_node(node);

    assert!(result.is_ok(), "Should insert node");
}

#[test]
fn test_storage_manager_node_count() {
    let temp_dir = tempfile::tempdir().unwrap();
    let db_path = temp_dir.path().join("test.db");
    let mut storage = StorageManager::create(&db_path).unwrap();

    for i in 0..10 {
        let node = NodeRec {
            id: i,
            morton_code: i,
            x: i as f32,
            y: i as f32,
            z: i as f32,
            edge_off: 0,
            edge_len: 0,
            flags: 0,
            begin_ts: 0,
            end_ts: 0,
            tx_id: 0,
            visibility: 1,
            _padding: [0; 7],
        };
        storage.insert_node(node).unwrap();
    }

    assert_eq!(storage.node_count(), 10, "Should have 10 nodes");
}

#[test]
fn test_storage_manager_persistence() {
    let temp_dir = tempfile::tempdir().unwrap();
    let db_path = temp_dir.path().join("test.db");

    // Create and insert
    {
        let mut storage = StorageManager::create(&db_path).unwrap();
        let node = NodeRec {
            id: 99,
            morton_code: 12345,
            x: 1.0,
            y: 2.0,
            z: 3.0,
            edge_off: 0,
            edge_len: 0,
            flags: 0,
            begin_ts: 0,
            end_ts: 0,
            tx_id: 0,
            visibility: 1,
            _padding: [0; 7],
        };
        storage.insert_node(node).unwrap();
    } // Storage dropped, data flushed

    // Re-open and verify
    {
        let storage = StorageManager::open(&db_path).unwrap();
        let retrieved = storage.get_node(0);

        assert!(retrieved.is_some(), "Node should persist");
        let node = retrieved.unwrap();
        assert_eq!(node.id, 99, "ID should match");
        assert_eq!(node.morton_code, 12345, "Morton code should match");
        assert_eq!(node.x, 1.0, "X should match");
        assert_eq!(storage.node_count(), 1, "Node count should persist");
    }
}
