iwcore 0.1.25

IntelliWallet Core - Password manager library with AES-256 encryption
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
//! Main Wallet API
//!
//! This module provides the primary interface for interacting with
//! an IntelliWallet database.

use std::path::{Path, PathBuf};
use std::collections::HashMap;
use crate::error::{WalletError, Result};
use crate::database::{Database, IWItem, IWField, IWLabel, IWProperties};
use crate::database::queries::{self, parse_timestamp};
use crate::database::migrations;
use crate::crypto;
use crate::utils::generate_database_id;
use crate::{DATABASE_FILENAME, ROOT_ID, ROOT_PARENT_ID, DB_VERSION, ENCRYPTION_COUNT_DEFAULT};

/// Main wallet interface
pub struct Wallet {
    /// Path to the wallet folder
    pub(crate) folder: PathBuf,
    /// Database connection
    pub(crate) db: Option<Database>,
    /// Current password (when unlocked)
    pub(crate) password: Option<String>,
    /// Encryption iteration count
    pub(crate) encryption_count: u32,
    /// Cached items (decrypted)
    pub(crate) items_cache: Option<Vec<IWItem>>,
    /// Cached fields (decrypted)
    pub(crate) fields_cache: Option<Vec<IWField>>,
    /// Cached labels
    pub(crate) labels_cache: Option<HashMap<String, IWLabel>>,
}

impl Wallet {
    /// Open a wallet from a folder
    ///
    /// The folder should contain a `nswallet.dat` file. Runs any pending
    /// schema migrations as part of opening so that databases coming from
    /// older app versions (whether on disk from an older install or freshly
    /// imported via restore) get their schema and version field brought
    /// up to `DB_VERSION` before any other code touches them.
    pub fn open(folder: &Path) -> Result<Self> {
        let db_path = folder.join(DATABASE_FILENAME);

        if !db_path.exists() {
            return Err(WalletError::DatabaseNotFound(
                db_path.to_string_lossy().to_string()
            ));
        }

        let db = Database::open(&db_path)?;

        // Apply pending migrations. Idempotent on already-current DBs.
        // Migrations operate on plaintext schema and label rows, so they
        // don't need the master password — safe to run pre-unlock.
        {
            let conn = db.connection()?;
            let current = migrations::get_database_version(conn)?;
            migrations::upgrade_database(conn, &current)?;
        }

        Ok(Self {
            folder: folder.to_path_buf(),
            db: Some(db),
            password: None,
            encryption_count: ENCRYPTION_COUNT_DEFAULT,
            items_cache: None,
            fields_cache: None,
            labels_cache: None,
        })
    }

    /// Create a new wallet in the specified folder
    pub fn create(folder: &Path, password: &str, lang: &str) -> Result<Self> {
        std::fs::create_dir_all(folder)?;

        let db_path = folder.join(DATABASE_FILENAME);
        let db = Database::create(&db_path)?;

        let mut wallet = Self {
            folder: folder.to_path_buf(),
            db: Some(db),
            password: Some(password.to_string()),
            encryption_count: 0, // New databases use 0
            items_cache: None,
            fields_cache: None,
            labels_cache: None,
        };

        // Initialize the database with required data
        wallet.init_new_database(password, lang)?;

        Ok(wallet)
    }

    /// Initialize a new database with properties and root item
    fn init_new_database(&mut self, password: &str, lang: &str) -> Result<()> {
        let conn = self.db.as_ref()
            .ok_or_else(|| WalletError::DatabaseError("Database not open".to_string()))?
            .connection()?;

        // Create properties
        let db_id = generate_database_id();
        queries::set_properties(conn, &db_id, lang, DB_VERSION, 0)?;

        // Create root item with encrypted random string
        let root_data = crate::utils::generate_id(32);
        let encrypted = crypto::encrypt(&root_data, password, 0, None)
            .map_err(|e| WalletError::EncryptionError(e))?;
        queries::create_item(conn, ROOT_ID, ROOT_PARENT_ID, &encrypted, "", true)?;

        // Add system labels
        self.add_system_labels()?;

        Ok(())
    }

    /// Unlock the wallet with a password
    pub fn unlock(&mut self, password: &str) -> Result<bool> {
        // Try to decrypt the root item to verify password
        let db = self.db.as_ref().ok_or(WalletError::DatabaseError(
            "Database not open".to_string()
        ))?;

        let conn = db.connection()?;

        // Get root item's encrypted name
        let root_name = queries::get_root_item_raw(conn)?;

        let Some(encrypted_name) = root_name else {
            return Err(WalletError::DatabaseError("Root item not found".to_string()));
        };

        // Get encryption count from properties
        if let Some(props) = queries::get_properties(conn)? {
            self.encryption_count = props.email.parse().unwrap_or(ENCRYPTION_COUNT_DEFAULT);
        }

        // Try to decrypt
        match crypto::decrypt(&encrypted_name, password, self.encryption_count, None) {
            Ok(_) => {
                self.password = Some(password.to_string());
                self.clear_caches();
                // Ensure any new system labels are added to existing wallets
                self.add_system_labels()?;
                Ok(true)
            }
            Err(_) => Ok(false)
        }
    }

    /// Lock the wallet
    pub fn lock(&mut self) {
        self.password = None;
        self.clear_caches();
    }

    /// Check if the wallet is unlocked
    pub fn is_unlocked(&self) -> bool {
        self.password.is_some()
    }

    /// Close the wallet
    pub fn close(&mut self) {
        self.lock();
        if let Some(mut db) = self.db.take() {
            db.close();
        }
    }

    /// Clear all caches
    pub(crate) fn clear_caches(&mut self) {
        self.items_cache = None;
        self.fields_cache = None;
        self.labels_cache = None;
    }

    /// Get the wallet folder path
    pub fn folder(&self) -> &Path {
        &self.folder
    }

    /// Check password without unlocking
    pub fn check_password(&self, password: &str) -> Result<bool> {
        let db = self.db.as_ref().ok_or(WalletError::DatabaseError(
            "Database not open".to_string()
        ))?;

        let conn = db.connection()?;

        let root_name = queries::get_root_item_raw(conn)?;

        let Some(encrypted_name) = root_name else {
            return Err(WalletError::DatabaseError("Root item not found".to_string()));
        };

        let encryption_count = if let Some(props) = queries::get_properties(conn)? {
            props.email.parse().unwrap_or(ENCRYPTION_COUNT_DEFAULT)
        } else {
            self.encryption_count
        };

        match crypto::decrypt(&encrypted_name, password, encryption_count, None) {
            Ok(_) => Ok(true),
            Err(_) => Ok(false)
        }
    }

    /// Get database properties
    pub fn get_properties(&self) -> Result<IWProperties> {
        let db = self.db.as_ref().ok_or(WalletError::DatabaseError(
            "Database not open".to_string()
        ))?;

        let conn = db.connection()?;

        let raw_props = queries::get_properties(conn)?
            .ok_or_else(|| WalletError::DatabaseError("Properties not found".to_string()))?;

        Ok(IWProperties {
            database_id: raw_props.database_id,
            lang: raw_props.lang,
            version: raw_props.version,
            encryption_count: raw_props.email.parse().unwrap_or(ENCRYPTION_COUNT_DEFAULT),
            sync_timestamp: raw_props.sync_timestamp.as_ref().and_then(|s| parse_timestamp(s)),
            update_timestamp: raw_props.update_timestamp.as_ref().and_then(|s| parse_timestamp(s)),
        })
    }

    /// Change the wallet password (re-encrypts all data)
    pub fn change_password(&mut self, new_password: &str) -> Result<bool> {
        self.ensure_unlocked()?;

        let old_password = self.password.as_ref().unwrap().clone();

        // Load all data first
        self.load_items_if_needed()?;
        self.load_fields_if_needed()?;

        let items = self.items_cache.take().unwrap();
        let fields = self.fields_cache.take().unwrap();
        let encryption_count = self.encryption_count;

        let db = self.db.as_mut()
            .ok_or_else(|| WalletError::DatabaseError("Database not open".to_string()))?;

        db.begin_transaction()?;

        let result = (|| -> Result<()> {
            let conn = db.connection()?;

            // Re-encrypt all active items
            for item in &items {
                let new_encrypted = crypto::encrypt(&item.name, new_password, encryption_count, None)
                    .map_err(|e| WalletError::EncryptionError(e))?;
                queries::update_item_name_only(conn, &item.item_id, &new_encrypted)?;
            }

            // Re-encrypt all active fields
            for field in &fields {
                let new_encrypted = crypto::encrypt(&field.value, new_password, encryption_count, None)
                    .map_err(|e| WalletError::EncryptionError(e))?;
                queries::update_field_value_only(conn, &field.item_id, &field.field_id, &new_encrypted)?;
            }

            // Re-encrypt deleted items
            let deleted_items_raw = queries::get_deleted_items_raw(conn)?;
            for raw in &deleted_items_raw {
                if let Ok(name) = crypto::decrypt(&raw.name_encrypted, &old_password, encryption_count, None) {
                    let new_encrypted = crypto::encrypt(&name, new_password, encryption_count, None)
                        .map_err(|e| WalletError::EncryptionError(e))?;
                    queries::update_item_name_only(conn, &raw.item_id, &new_encrypted)?;
                }
            }

            // Re-encrypt deleted fields
            let deleted_fields_raw = queries::get_deleted_fields_raw(conn)?;
            for raw in &deleted_fields_raw {
                if let Ok(value) = crypto::decrypt(&raw.value_encrypted, &old_password, encryption_count, None) {
                    let new_encrypted = crypto::encrypt(&value, new_password, encryption_count, None)
                        .map_err(|e| WalletError::EncryptionError(e))?;
                    queries::update_field_value_only(conn, &raw.item_id, &raw.field_id, &new_encrypted)?;
                }
            }

            Ok(())
        })();

        match result {
            Ok(()) => {
                db.commit_transaction()?;
                self.password = Some(new_password.to_string());
                self.clear_caches();
                Ok(true)
            }
            Err(e) => {
                db.rollback_transaction()?;
                self.password = Some(old_password);
                self.items_cache = Some(items);
                self.fields_cache = Some(fields);
                Err(e)
            }
        }
    }

    /// Ensure wallet is unlocked
    pub(crate) fn ensure_unlocked(&self) -> Result<()> {
        if self.password.is_none() {
            return Err(WalletError::Locked);
        }
        Ok(())
    }

    /// Get the database path
    pub fn database_path(&self) -> PathBuf {
        self.folder.join(DATABASE_FILENAME)
    }

    /// Permanently purge all soft-deleted records and orphaned fields.
    /// Returns (purged_items_count, purged_fields_count).
    pub fn compact(&mut self) -> Result<(u32, u32)> {
        self.ensure_unlocked()?;

        let conn = self.db.as_ref()
            .ok_or_else(|| WalletError::DatabaseError("Database not open".to_string()))?
            .connection()?;

        let result = queries::purge_deleted(conn)?;

        self.clear_caches();
        Ok(result)
    }

    /// Get database statistics (counts of items, fields, labels, deleted records, file size)
    pub fn get_database_stats(&self) -> Result<queries::DatabaseStats> {
        let conn = self.db.as_ref()
            .ok_or_else(|| WalletError::DatabaseError("Database not open".to_string()))?
            .connection()?;

        let mut stats = queries::get_database_stats(conn)?;

        // Set file size from filesystem metadata
        let db_path = self.database_path();
        if let Ok(metadata) = std::fs::metadata(&db_path) {
            stats.file_size_bytes = metadata.len();
        }

        Ok(stats)
    }

    /// Get a reference to the database for backup operations
    pub fn database(&self) -> Result<&Database> {
        self.db.as_ref().ok_or_else(|| WalletError::DatabaseError("Database not open".to_string()))
    }
}

impl Drop for Wallet {
    fn drop(&mut self) {
        self.close();
    }
}

#[cfg(test)]
pub(crate) mod tests {
    use super::*;
    use tempfile::TempDir;
    use crate::DB_VERSION;

    pub fn create_test_wallet() -> (Wallet, TempDir) {
        let temp_dir = TempDir::new().unwrap();
        let wallet = Wallet::create(temp_dir.path(), "TestPassword123", "en").unwrap();
        (wallet, temp_dir)
    }

    #[test]
    fn test_create_and_unlock() {
        let (mut wallet, _temp) = create_test_wallet();
        wallet.lock();
        assert!(!wallet.is_unlocked());
        assert!(wallet.unlock("TestPassword123").unwrap());
        assert!(wallet.is_unlocked());
    }

    #[test]
    fn test_open_migrates_old_database() {
        // Simulate the "imported v4 backup" scenario: drop an old-version
        // database file into a folder, then call Wallet::open() and confirm
        // the version field is bumped without ever calling unlock().
        use rusqlite::Connection;
        let temp_dir = TempDir::new().unwrap();
        let wallet = Wallet::create(temp_dir.path(), "TestPassword123", "en").unwrap();
        let folder = temp_dir.path().to_path_buf();
        drop(wallet);

        // Force the version field back to "4" to simulate an older DB.
        let db_path = folder.join(crate::DATABASE_FILENAME);
        let conn = Connection::open(&db_path).unwrap();
        conn.execute("UPDATE nswallet_properties SET version = ?", ["4"]).unwrap();
        drop(conn);

        // Re-open the wallet — migrations should run and bump the version.
        let _ = Wallet::open(&folder).unwrap();

        let conn = Connection::open(&db_path).unwrap();
        let v: String = conn
            .query_row(
                "SELECT version FROM nswallet_properties LIMIT 1",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(v, DB_VERSION);

        // SEED label (added by the v4→v5 migration) must now be present.
        let seed_count: i32 = conn
            .query_row(
                "SELECT COUNT(*) FROM nswallet_labels WHERE field_type = 'SEED'",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(seed_count, 1);
    }

    #[test]
    fn test_open_no_op_on_current_database() {
        // Open a fresh DB twice; the second open shouldn't change anything
        // version-wise.
        let temp_dir = TempDir::new().unwrap();
        let wallet = Wallet::create(temp_dir.path(), "TestPassword123", "en").unwrap();
        let folder = temp_dir.path().to_path_buf();
        drop(wallet);

        // Re-open — should be a no-op for migration purposes.
        let _ = Wallet::open(&folder).unwrap();

        use rusqlite::Connection;
        let db_path = folder.join(crate::DATABASE_FILENAME);
        let conn = Connection::open(&db_path).unwrap();
        let v: String = conn
            .query_row(
                "SELECT version FROM nswallet_properties LIMIT 1",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(v, DB_VERSION);
    }

    #[test]
    fn test_wrong_password() {
        let (mut wallet, _temp) = create_test_wallet();
        wallet.lock();
        assert!(!wallet.unlock("WrongPassword").unwrap());
        assert!(!wallet.is_unlocked());
    }

    #[test]
    fn test_properties() {
        let (wallet, _temp) = create_test_wallet();
        let props = wallet.get_properties().unwrap();
        assert_eq!(props.lang, "en");
        assert_eq!(props.version, DB_VERSION);
        assert_eq!(props.encryption_count, 0);
        assert_eq!(props.database_id.len(), 32);
    }

    #[test]
    fn test_change_password() {
        let (mut wallet, _temp) = create_test_wallet();
        let item_id = wallet.add_item("Test Item", "document", false, None).unwrap();
        wallet.add_field(&item_id, "PASS", "secret123", None).unwrap();

        assert!(wallet.change_password("NewPassword456").unwrap());

        wallet.lock();
        assert!(!wallet.unlock("TestPassword123").unwrap());
        assert!(wallet.unlock("NewPassword456").unwrap());

        let fields = wallet.get_fields_by_item(&item_id).unwrap();
        assert_eq!(fields[0].value, "secret123");
    }

    #[test]
    fn test_wallet_folder() {
        let (wallet, temp) = create_test_wallet();
        assert_eq!(wallet.folder(), temp.path());
    }

    #[test]
    fn test_database_path() {
        let (wallet, temp) = create_test_wallet();
        assert_eq!(wallet.database_path(), temp.path().join("nswallet.dat"));
    }

    #[test]
    fn test_open_nonexistent() {
        let result = Wallet::open(std::path::Path::new("/nonexistent/path"));
        assert!(result.is_err());
    }

    #[test]
    fn test_check_password() {
        let (mut wallet, _temp) = create_test_wallet();
        wallet.lock();
        assert!(wallet.check_password("TestPassword123").unwrap());
        assert!(!wallet.check_password("WrongPassword").unwrap());
    }

    /// Creates a wallet encrypted with the given encryption_count.
    /// Re-encrypts root item and updates DB properties accordingly.
    fn create_wallet_with_encryption_count(encryption_count: u32) -> (TempDir, std::path::PathBuf) {
        let temp_dir = TempDir::new().unwrap();
        let path = temp_dir.path().to_path_buf();
        let password = "TestPassword123";

        // Create wallet (encryption_count=0 by default)
        let wallet = Wallet::create(&path, password, "en").unwrap();
        let db = wallet.db.as_ref().unwrap();
        let conn = db.connection().unwrap();

        // Re-encrypt root item with the target encryption_count
        let root_raw = queries::get_root_item_raw(conn).unwrap().unwrap();
        let plaintext = crypto::decrypt(&root_raw, password, 0, None).unwrap();
        let new_encrypted = crypto::encrypt(&plaintext, password, encryption_count, None).unwrap();
        conn.execute(
            "UPDATE nswallet_items SET name = ? WHERE item_id = '__ROOT__'",
            rusqlite::params![new_encrypted],
        ).unwrap();

        // Update stored encryption_count in properties
        conn.execute(
            "UPDATE nswallet_properties SET email = ?",
            rusqlite::params![encryption_count.to_string()],
        ).unwrap();

        assert_eq!(wallet.get_properties().unwrap().encryption_count, encryption_count);
        drop(wallet);
        (temp_dir, path)
    }

    #[test]
    fn test_check_password_after_reopen_enc0() {
        let (_temp, path) = create_wallet_with_encryption_count(0);
        let wallet = Wallet::open(&path).unwrap();
        assert!(wallet.check_password("TestPassword123").unwrap());
        assert!(!wallet.check_password("WrongPassword").unwrap());
    }

    #[test]
    fn test_check_password_after_reopen_enc33() {
        let (_temp, path) = create_wallet_with_encryption_count(33);
        let wallet = Wallet::open(&path).unwrap();
        assert!(wallet.check_password("TestPassword123").unwrap());
        assert!(!wallet.check_password("WrongPassword").unwrap());
    }

    #[test]
    fn test_check_password_after_reopen_enc200() {
        let (_temp, path) = create_wallet_with_encryption_count(200);
        let wallet = Wallet::open(&path).unwrap();
        assert!(wallet.check_password("TestPassword123").unwrap());
        assert!(!wallet.check_password("WrongPassword").unwrap());
    }

    #[test]
    fn test_check_password_after_reopen_enc500() {
        let (_temp, path) = create_wallet_with_encryption_count(500);
        let wallet = Wallet::open(&path).unwrap();
        assert!(wallet.check_password("TestPassword123").unwrap());
        assert!(!wallet.check_password("WrongPassword").unwrap());
    }

    #[test]
    fn test_compact_items() {
        let (mut wallet, _temp) = create_test_wallet();
        let item_id = wallet.add_item("To Purge", "document", false, None).unwrap();
        wallet.delete_item(&item_id).unwrap();

        wallet.compact().unwrap();

        let deleted = wallet.get_deleted_items().unwrap();
        assert!(deleted.is_empty());
    }

    #[test]
    fn test_compact_fields() {
        let (mut wallet, _temp) = create_test_wallet();
        let item_id = wallet.add_item("Item", "document", false, None).unwrap();
        let field_id = wallet.add_field(&item_id, "MAIL", "purge@test.com", None).unwrap();
        wallet.delete_field(&item_id, &field_id).unwrap();

        wallet.compact().unwrap();

        let deleted = wallet.get_deleted_fields().unwrap();
        assert!(deleted.is_empty());
    }

    #[test]
    fn test_compact_cascaded_fields() {
        let (mut wallet, _temp) = create_test_wallet();
        let item_id = wallet.add_item("Item", "document", false, None).unwrap();
        wallet.add_field(&item_id, "MAIL", "orphan@test.com", None).unwrap();
        wallet.add_field(&item_id, "PASS", "secret", None).unwrap();

        // Delete item (fields are cascade soft-deleted)
        wallet.delete_item(&item_id).unwrap();

        wallet.compact().unwrap();

        // Cascade-deleted fields should also be purged
        let deleted_fields = wallet.get_deleted_fields().unwrap();
        assert!(deleted_fields.is_empty());
        let deleted_items = wallet.get_deleted_items().unwrap();
        assert!(deleted_items.is_empty());
    }

    #[test]
    fn test_compact_returns_counts() {
        let (mut wallet, _temp) = create_test_wallet();
        let item1_id = wallet.add_item("Item 1", "document", false, None).unwrap();
        let item2_id = wallet.add_item("Item 2", "document", false, None).unwrap();
        let _field_id = wallet.add_field(&item1_id, "MAIL", "test@test.com", None).unwrap();

        // delete_item cascades to fields now, so field is already deleted=1
        wallet.delete_item(&item1_id).unwrap();
        wallet.delete_item(&item2_id).unwrap();

        let (items_count, fields_count) = wallet.compact().unwrap();
        assert_eq!(items_count, 2);
        assert_eq!(fields_count, 1); // cascade-deleted field
    }

    #[test]
    fn test_compact_empty() {
        let (mut wallet, _temp) = create_test_wallet();
        let (items, fields) = wallet.compact().unwrap();
        assert_eq!(items, 0);
        assert_eq!(fields, 0);
    }

    #[test]
    fn test_compact_preserves_active_records() {
        let (mut wallet, _temp) = create_test_wallet();
        let item1 = wallet.add_item("Keep This", "document", false, None).unwrap();
        wallet.add_field(&item1, "MAIL", "keep@test.com", None).unwrap();
        let item2 = wallet.add_item("Delete This", "document", false, None).unwrap();
        wallet.add_field(&item2, "PASS", "gone", None).unwrap();

        wallet.delete_item(&item2).unwrap();
        wallet.compact().unwrap();

        // Active records untouched
        let item = wallet.get_item(&item1).unwrap().unwrap();
        assert_eq!(item.name, "Keep This");
        let fields = wallet.get_fields_by_item(&item1).unwrap();
        assert_eq!(fields.len(), 1);
        assert_eq!(fields[0].value, "keep@test.com");
    }

    #[test]
    fn test_compact_double_call_idempotent() {
        let (mut wallet, _temp) = create_test_wallet();
        let item_id = wallet.add_item("Delete Me", "document", false, None).unwrap();
        wallet.delete_item(&item_id).unwrap();

        let (i1, _f1) = wallet.compact().unwrap();
        assert_eq!(i1, 1);

        // Second compact: nothing left to purge
        let (i2, f2) = wallet.compact().unwrap();
        assert_eq!(i2, 0);
        assert_eq!(f2, 0);
    }

    #[test]
    fn test_compact_after_cascade_delete() {
        let (mut wallet, _temp) = create_test_wallet();
        let folder = wallet.add_item("Folder", "folder", true, None).unwrap();
        let child1 = wallet.add_item("Child 1", "document", false, Some(&folder)).unwrap();
        let child2 = wallet.add_item("Child 2", "document", false, Some(&folder)).unwrap();
        wallet.add_field(&child1, "MAIL", "c1@test.com", None).unwrap();
        wallet.add_field(&child2, "PASS", "secret", None).unwrap();

        wallet.delete_item(&folder).unwrap();

        let (items_count, fields_count) = wallet.compact().unwrap();
        assert_eq!(items_count, 3); // folder + 2 children
        assert_eq!(fields_count, 2); // cascade-deleted fields

        // Everything gone
        assert!(wallet.get_deleted_items().unwrap().is_empty());
        assert!(wallet.get_deleted_fields().unwrap().is_empty());
    }

    #[test]
    fn test_compact_mixed_deleted_and_cascaded_fields() {
        let (mut wallet, _temp) = create_test_wallet();
        let item_id = wallet.add_item("Item", "document", false, None).unwrap();
        let f1 = wallet.add_field(&item_id, "MAIL", "test@test.com", None).unwrap();
        wallet.add_field(&item_id, "PASS", "secret", None).unwrap();

        // Explicitly delete one field, then delete the item (cascade-deletes the other)
        wallet.delete_field(&item_id, &f1).unwrap();
        wallet.delete_item(&item_id).unwrap();

        let (items_count, fields_count) = wallet.compact().unwrap();
        assert_eq!(items_count, 1);
        // Both fields purged: f1 was explicitly soft-deleted, PASS was cascade-deleted
        assert_eq!(fields_count, 2);
    }

    #[test]
    fn test_compact_with_active_and_deleted_fields_same_item() {
        let (mut wallet, _temp) = create_test_wallet();
        let item_id = wallet.add_item("Item", "document", false, None).unwrap();
        let f_del = wallet.add_field(&item_id, "MAIL", "delete@me.com", None).unwrap();
        wallet.add_field(&item_id, "PASS", "keep_me", None).unwrap();

        wallet.delete_field(&item_id, &f_del).unwrap();
        wallet.compact().unwrap();

        // Deleted field gone
        assert!(wallet.get_deleted_fields().unwrap().is_empty());
        // Active field still there
        let active = wallet.get_fields_by_item(&item_id).unwrap();
        assert_eq!(active.len(), 1);
        assert_eq!(active[0].value, "keep_me");
    }

    #[test]
    fn test_database_stats() {
        let (mut wallet, _temp) = create_test_wallet();
        let folder = wallet.add_item("Folder", "folder", true, None).unwrap();
        let item1 = wallet.add_item("Item 1", "document", false, None).unwrap();
        let item2 = wallet.add_item("Item 2", "document", false, Some(&folder)).unwrap();
        wallet.add_field(&item1, "MAIL", "a@a.com", None).unwrap();
        wallet.add_field(&item1, "PASS", "secret", None).unwrap();
        wallet.add_field(&item2, "NOTE", "note", None).unwrap();

        // Delete one item (cascades to its fields)
        wallet.delete_item(&item2).unwrap();

        let stats = wallet.get_database_stats().unwrap();
        assert_eq!(stats.total_items, 1);    // item1 (item2 deleted)
        assert_eq!(stats.total_folders, 1);  // folder
        assert_eq!(stats.total_fields, 2);   // item1's 2 fields (item2's field cascade-deleted)
        assert_eq!(stats.deleted_items, 1);  // item2
        assert_eq!(stats.deleted_fields, 1); // item2's cascade-deleted field
        assert!(stats.total_labels >= 19);   // system labels
        assert!(stats.file_size_bytes > 0);
    }

    #[test]
    fn test_change_password_reencrypts_deleted_items() {
        let (mut wallet, _temp) = create_test_wallet();
        let item_id = wallet.add_item("Deleted Item", "document", false, None).unwrap();
        wallet.delete_item(&item_id).unwrap();

        // Change password
        assert!(wallet.change_password("NewPassword456").unwrap());

        // Deleted item should still be accessible after password change
        let deleted = wallet.get_deleted_items().unwrap();
        assert_eq!(deleted.len(), 1);
        assert_eq!(deleted[0].name, "Deleted Item");

        // Verify new password works after reopen
        wallet.lock();
        assert!(wallet.unlock("NewPassword456").unwrap());
        let deleted2 = wallet.get_deleted_items().unwrap();
        assert_eq!(deleted2.len(), 1);
        assert_eq!(deleted2[0].name, "Deleted Item");
    }

    #[test]
    fn test_change_password_reencrypts_deleted_fields() {
        let (mut wallet, _temp) = create_test_wallet();
        let item_id = wallet.add_item("Item", "document", false, None).unwrap();
        let field_id = wallet.add_field(&item_id, "PASS", "my_secret", None).unwrap();
        wallet.delete_field(&item_id, &field_id).unwrap();

        // Change password
        assert!(wallet.change_password("NewPassword456").unwrap());

        // Deleted field should still be accessible after password change
        let deleted = wallet.get_deleted_fields().unwrap();
        assert_eq!(deleted.len(), 1);
        assert_eq!(deleted[0].value, "my_secret");

        // Verify new password works after reopen
        wallet.lock();
        assert!(wallet.unlock("NewPassword456").unwrap());
        let deleted2 = wallet.get_deleted_fields().unwrap();
        assert_eq!(deleted2.len(), 1);
        assert_eq!(deleted2[0].value, "my_secret");
    }

    #[test]
    fn test_change_password_reencrypts_cascade_deleted_fields() {
        let (mut wallet, _temp) = create_test_wallet();
        let item_id = wallet.add_item("Item", "document", false, None).unwrap();
        wallet.add_field(&item_id, "MAIL", "cascade@test.com", None).unwrap();
        wallet.add_field(&item_id, "PASS", "cascade_secret", None).unwrap();

        // Delete item — fields become cascade-deleted (deleted=1)
        wallet.delete_item(&item_id).unwrap();

        // Verify cascade-deleted fields are in deleted list
        let deleted_before = wallet.get_deleted_fields().unwrap();
        let our_fields: Vec<_> = deleted_before.iter().filter(|f| f.item_id == item_id).collect();
        assert_eq!(our_fields.len(), 2);

        // Change password
        assert!(wallet.change_password("NewPassword456").unwrap());

        // Cascade-deleted fields should still be accessible after password change
        let deleted_after = wallet.get_deleted_fields().unwrap();
        let our_fields_after: Vec<_> = deleted_after.iter().filter(|f| f.item_id == item_id).collect();
        assert_eq!(our_fields_after.len(), 2);
        let values: Vec<&str> = our_fields_after.iter().map(|f| f.value.as_str()).collect();
        assert!(values.contains(&"cascade@test.com"));
        assert!(values.contains(&"cascade_secret"));

        // Verify after lock/unlock with new password
        wallet.lock();
        assert!(wallet.unlock("NewPassword456").unwrap());
        let deleted_reopen = wallet.get_deleted_fields().unwrap();
        let our_fields_reopen: Vec<_> = deleted_reopen.iter().filter(|f| f.item_id == item_id).collect();
        assert_eq!(our_fields_reopen.len(), 2);
    }

    #[test]
    fn test_change_password_mixed_active_and_deleted() {
        let (mut wallet, _temp) = create_test_wallet();
        let active_item = wallet.add_item("Active Item", "document", false, None).unwrap();
        wallet.add_field(&active_item, "MAIL", "active@test.com", None).unwrap();

        let del_item = wallet.add_item("Deleted Item", "document", false, None).unwrap();
        let del_field = wallet.add_field(&del_item, "PASS", "deleted_secret", None).unwrap();
        wallet.delete_item(&del_item).unwrap();
        wallet.delete_field(&del_item, &del_field).unwrap();

        assert!(wallet.change_password("NewPassword456").unwrap());

        // Active records still work
        let item = wallet.get_item(&active_item).unwrap().unwrap();
        assert_eq!(item.name, "Active Item");
        let fields = wallet.get_fields_by_item(&active_item).unwrap();
        assert_eq!(fields[0].value, "active@test.com");

        // Deleted records also still work
        let deleted_items = wallet.get_deleted_items().unwrap();
        assert_eq!(deleted_items.len(), 1);
        assert_eq!(deleted_items[0].name, "Deleted Item");

        let deleted_fields = wallet.get_deleted_fields().unwrap();
        assert_eq!(deleted_fields.len(), 1);
        assert_eq!(deleted_fields[0].value, "deleted_secret");
    }
}