leptos-store 0.5.0

Enterprise-grade, type-enforced state management for Leptos
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
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
// SPDX-License-Identifier: Apache-2.0
// Copyright 2026 web-mech

//! Persistence adapters for store state.
//!
//! This module provides infrastructure for persisting store state across
//! sessions using various storage backends.
//!
//! # Available Adapters
//!
//! | Adapter | Feature | Platform | Description |
//! |---------|---------|----------|-------------|
//! | `MemoryAdapter` | default | All | In-memory storage (testing) |
//! | `LocalStorageAdapter` | `persist-web` | WASM | Browser localStorage |
//! | `SessionStorageAdapter` | `persist-web` | WASM | Browser sessionStorage |
//! | `IndexedDbAdapter` | `persist-idb` | WASM | IndexedDB for larger data |
//! | `ServerSyncAdapter` | `persist-server` | SSR | Server-side persistence |
//!
//! # Example
//!
//! ```rust,ignore
//! use leptos_store::persistence::*;
//!
//! let store = MyStore::new();
//! let persistent = PersistentStore::new(store, LocalStorageAdapter::new())
//!     .with_key("my_store")
//!     .with_debounce(500);
//! ```

use crate::store::Store;
use leptos::prelude::GetUntracked;
use std::collections::HashMap;
use std::fmt;
use std::future::Future;
use std::marker::PhantomData;
use std::pin::Pin;
use std::sync::{Arc, RwLock};
use thiserror::Error;

// ============================================================================
// Persistence Errors
// ============================================================================

/// Errors that can occur during persistence operations.
#[derive(Debug, Error, Clone)]
pub enum PersistError {
    /// Failed to serialize state.
    #[error("Serialization error: {0}")]
    Serialization(String),

    /// Failed to deserialize state.
    #[error("Deserialization error: {0}")]
    Deserialization(String),

    /// Storage is not available.
    #[error("Storage not available: {0}")]
    NotAvailable(String),

    /// Storage quota exceeded.
    #[error("Storage quota exceeded")]
    QuotaExceeded,

    /// Key not found.
    #[error("Key not found: {0}")]
    NotFound(String),

    /// Permission denied.
    #[error("Permission denied: {0}")]
    PermissionDenied(String),

    /// Network error (for server sync).
    #[error("Network error: {0}")]
    Network(String),

    /// Version mismatch during migration.
    #[error("Version mismatch: expected {expected}, found {found}")]
    VersionMismatch {
        /// The expected version number.
        expected: u32,
        /// The actual version number found.
        found: u32,
    },

    /// Internal error.
    #[error("Internal error: {0}")]
    Internal(String),
}

/// Result type for persistence operations.
pub type PersistResult<T> = Result<T, PersistError>;

// ============================================================================
// Storage Types
// ============================================================================

/// Types of storage backends.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StorageType {
    /// In-memory storage (volatile).
    Memory,
    /// Browser localStorage (persistent, synchronous).
    LocalStorage,
    /// Browser sessionStorage (session-scoped).
    SessionStorage,
    /// IndexedDB (persistent, asynchronous, larger capacity).
    IndexedDb,
    /// Server-side storage.
    Server,
    /// Custom storage implementation.
    Custom,
}

impl fmt::Display for StorageType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Memory => write!(f, "Memory"),
            Self::LocalStorage => write!(f, "LocalStorage"),
            Self::SessionStorage => write!(f, "SessionStorage"),
            Self::IndexedDb => write!(f, "IndexedDB"),
            Self::Server => write!(f, "Server"),
            Self::Custom => write!(f, "Custom"),
        }
    }
}

// ============================================================================
// Persistence Adapter Trait
// ============================================================================

/// Future type for async persistence operations.
///
/// On native targets, this requires `Send` for thread safety.
/// On WASM, `Send` is not required (single-threaded environment).
#[cfg(not(target_arch = "wasm32"))]
pub type PersistFuture<'a, T> = Pin<Box<dyn Future<Output = PersistResult<T>> + Send + 'a>>;

/// Future type for async persistence operations (WASM version).
#[cfg(target_arch = "wasm32")]
pub type PersistFuture<'a, T> = Pin<Box<dyn Future<Output = PersistResult<T>> + 'a>>;

/// Trait for persistence adapters.
///
/// Adapters provide the interface between stores and storage backends.
/// All operations are async to support both sync (localStorage) and
/// async (IndexedDB) backends uniformly.
///
/// # Example
///
/// ```rust,no_run
/// use leptos_store::persistence::{PersistenceAdapter, PersistFuture, StorageType};
///
/// struct MyAdapter;
///
/// impl PersistenceAdapter for MyAdapter {
///     fn save<'a>(&'a self, key: &'a str, data: &'a [u8]) -> PersistFuture<'a, ()> {
///         Box::pin(async move {
///             // Save data to your backend
///             Ok(())
///         })
///     }
///
///     fn load<'a>(&'a self, key: &'a str) -> PersistFuture<'a, Option<Vec<u8>>> {
///         Box::pin(async move {
///             // Load data from your backend
///             Ok(None)
///         })
///     }
///
///     fn remove<'a>(&'a self, key: &'a str) -> PersistFuture<'a, ()> {
///         Box::pin(async move {
///             // Remove data from your backend
///             Ok(())
///         })
///     }
///
///     fn storage_type(&self) -> StorageType {
///         StorageType::Custom
///     }
/// }
/// ```
pub trait PersistenceAdapter: Send + Sync {
    /// Save data to storage.
    fn save<'a>(&'a self, key: &'a str, data: &'a [u8]) -> PersistFuture<'a, ()>;

    /// Load data from storage.
    fn load<'a>(&'a self, key: &'a str) -> PersistFuture<'a, Option<Vec<u8>>>;

    /// Remove data from storage.
    fn remove<'a>(&'a self, key: &'a str) -> PersistFuture<'a, ()>;

    /// Get the storage type.
    fn storage_type(&self) -> StorageType;

    /// Check if the adapter is available.
    fn is_available(&self) -> bool {
        true
    }

    /// Get storage capacity info (if available).
    fn capacity(&self) -> Option<StorageCapacity> {
        None
    }

    /// Clear all data from this adapter's namespace.
    fn clear<'a>(&'a self) -> PersistFuture<'a, ()> {
        Box::pin(async { Ok(()) })
    }

    /// List all keys in this adapter's namespace.
    fn keys<'a>(&'a self) -> PersistFuture<'a, Vec<String>> {
        Box::pin(async { Ok(Vec::new()) })
    }
}

/// Storage capacity information.
#[derive(Debug, Clone, Copy)]
pub struct StorageCapacity {
    /// Total capacity in bytes (if known).
    pub total: Option<u64>,
    /// Used capacity in bytes (if known).
    pub used: Option<u64>,
    /// Available capacity in bytes (if known).
    pub available: Option<u64>,
}

impl StorageCapacity {
    /// Create a new capacity info with all fields unknown.
    pub fn unknown() -> Self {
        Self {
            total: None,
            used: None,
            available: None,
        }
    }

    /// Create capacity info with known values.
    pub fn known(total: u64, used: u64) -> Self {
        Self {
            total: Some(total),
            used: Some(used),
            available: Some(total.saturating_sub(used)),
        }
    }
}

// ============================================================================
// Memory Adapter (Default)
// ============================================================================

/// In-memory persistence adapter for testing.
///
/// Data is stored in memory and is lost when the application restarts.
/// This is useful for testing and development.
#[derive(Clone)]
pub struct MemoryAdapter {
    storage: Arc<RwLock<HashMap<String, Vec<u8>>>>,
}

impl Default for MemoryAdapter {
    fn default() -> Self {
        Self::new()
    }
}

impl MemoryAdapter {
    /// Create a new memory adapter.
    pub fn new() -> Self {
        Self {
            storage: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    /// Create a memory adapter with initial data.
    pub fn with_data(data: HashMap<String, Vec<u8>>) -> Self {
        Self {
            storage: Arc::new(RwLock::new(data)),
        }
    }

    /// Get a snapshot of all data (for testing).
    pub fn snapshot(&self) -> HashMap<String, Vec<u8>> {
        self.storage.read().map(|s| s.clone()).unwrap_or_default()
    }

    /// Get the number of stored items.
    pub fn len(&self) -> usize {
        self.storage.read().map(|s| s.len()).unwrap_or(0)
    }

    /// Check if empty.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

impl PersistenceAdapter for MemoryAdapter {
    fn save<'a>(&'a self, key: &'a str, data: &'a [u8]) -> PersistFuture<'a, ()> {
        let storage = self.storage.clone();
        let key = key.to_string();
        let data = data.to_vec();

        Box::pin(async move {
            storage
                .write()
                .map_err(|e| PersistError::Internal(e.to_string()))?
                .insert(key, data);
            Ok(())
        })
    }

    fn load<'a>(&'a self, key: &'a str) -> PersistFuture<'a, Option<Vec<u8>>> {
        let storage = self.storage.clone();
        let key = key.to_string();

        Box::pin(async move {
            let data = storage
                .read()
                .map_err(|e| PersistError::Internal(e.to_string()))?
                .get(&key)
                .cloned();
            Ok(data)
        })
    }

    fn remove<'a>(&'a self, key: &'a str) -> PersistFuture<'a, ()> {
        let storage = self.storage.clone();
        let key = key.to_string();

        Box::pin(async move {
            storage
                .write()
                .map_err(|e| PersistError::Internal(e.to_string()))?
                .remove(&key);
            Ok(())
        })
    }

    fn storage_type(&self) -> StorageType {
        StorageType::Memory
    }

    fn clear<'a>(&'a self) -> PersistFuture<'a, ()> {
        let storage = self.storage.clone();

        Box::pin(async move {
            storage
                .write()
                .map_err(|e| PersistError::Internal(e.to_string()))?
                .clear();
            Ok(())
        })
    }

    fn keys<'a>(&'a self) -> PersistFuture<'a, Vec<String>> {
        let storage = self.storage.clone();

        Box::pin(async move {
            let keys = storage
                .read()
                .map_err(|e| PersistError::Internal(e.to_string()))?
                .keys()
                .cloned()
                .collect();
            Ok(keys)
        })
    }
}

impl fmt::Debug for MemoryAdapter {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("MemoryAdapter")
            .field("items", &self.len())
            .finish()
    }
}

// ============================================================================
// Persist Configuration
// ============================================================================

/// Configuration for persistent stores.
#[derive(Debug, Clone)]
pub struct PersistConfig {
    /// Storage key for this store.
    pub key: String,
    /// Debounce time in milliseconds (0 = no debounce).
    pub debounce_ms: u64,
    /// Version number for migrations.
    pub version: u32,
    /// Whether to auto-save on state changes.
    pub auto_save: bool,
    /// Whether to auto-load on store creation.
    pub auto_load: bool,
    /// Prefix for storage keys.
    pub key_prefix: String,
}

impl Default for PersistConfig {
    fn default() -> Self {
        Self {
            key: String::new(),
            debounce_ms: 100,
            version: 1,
            auto_save: true,
            auto_load: true,
            key_prefix: "leptos_store_".to_string(),
        }
    }
}

impl PersistConfig {
    /// Create a new config with the given key.
    pub fn new(key: impl Into<String>) -> Self {
        Self {
            key: key.into(),
            ..Default::default()
        }
    }

    /// Get the full storage key (prefix + key).
    pub fn full_key(&self) -> String {
        format!("{}{}", self.key_prefix, self.key)
    }
}

// ============================================================================
// Persisted State Wrapper
// ============================================================================

/// Wrapper for state that includes version information.
#[derive(Debug, Clone)]
pub struct PersistedState<State> {
    /// The actual state data.
    pub state: State,
    /// Version number for migration.
    pub version: u32,
    /// Timestamp when saved (milliseconds since epoch).
    pub saved_at: u64,
}

impl<State> PersistedState<State> {
    /// Create a new persisted state wrapper.
    pub fn new(state: State, version: u32) -> Self {
        Self {
            state,
            version,
            saved_at: current_timestamp_ms(),
        }
    }
}

// ============================================================================
// Persistent Store Wrapper
// ============================================================================

/// A store wrapper that adds persistence capabilities.
///
/// This wrapper automatically saves state changes to the configured
/// storage adapter and can restore state on initialization.
///
/// # Example
///
/// ```rust,ignore
/// use leptos_store::persistence::*;
///
/// let store = MyStore::new();
/// let persistent = PersistentStore::new(store, MemoryAdapter::new())
///     .with_key("my_store")
///     .with_debounce(500);
///
/// // State changes are automatically persisted
/// persistent.inner().set_count(42);
/// ```
pub struct PersistentStore<S, A>
where
    S: Store,
    A: PersistenceAdapter,
{
    inner: S,
    adapter: Arc<A>,
    config: PersistConfig,
    _marker: PhantomData<S::State>,
}

impl<S, A> Clone for PersistentStore<S, A>
where
    S: Store,
    A: PersistenceAdapter,
{
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
            adapter: Arc::clone(&self.adapter),
            config: self.config.clone(),
            _marker: PhantomData,
        }
    }
}

impl<S, A> PersistentStore<S, A>
where
    S: Store,
    A: PersistenceAdapter + 'static,
{
    /// Create a new persistent store.
    pub fn new(store: S, adapter: A) -> Self {
        Self {
            inner: store,
            adapter: Arc::new(adapter),
            config: PersistConfig::default(),
            _marker: PhantomData,
        }
    }

    /// Set the storage key.
    pub fn with_key(mut self, key: impl Into<String>) -> Self {
        self.config.key = key.into();
        self
    }

    /// Set the debounce time in milliseconds.
    pub fn with_debounce(mut self, ms: u64) -> Self {
        self.config.debounce_ms = ms;
        self
    }

    /// Set the version number for migrations.
    pub fn with_version(mut self, version: u32) -> Self {
        self.config.version = version;
        self
    }

    /// Enable or disable auto-save.
    pub fn with_auto_save(mut self, enabled: bool) -> Self {
        self.config.auto_save = enabled;
        self
    }

    /// Enable or disable auto-load.
    pub fn with_auto_load(mut self, enabled: bool) -> Self {
        self.config.auto_load = enabled;
        self
    }

    /// Set a custom key prefix.
    pub fn with_key_prefix(mut self, prefix: impl Into<String>) -> Self {
        self.config.key_prefix = prefix.into();
        self
    }

    /// Get the inner store.
    pub fn inner(&self) -> &S {
        &self.inner
    }

    /// Get mutable access to the inner store.
    pub fn inner_mut(&mut self) -> &mut S {
        &mut self.inner
    }

    /// Get the adapter.
    pub fn adapter(&self) -> &A {
        &self.adapter
    }

    /// Get the configuration.
    pub fn config(&self) -> &PersistConfig {
        &self.config
    }

    /// Get the full storage key.
    pub fn storage_key(&self) -> String {
        self.config.full_key()
    }
}

// Persistence operations for serializable state
impl<S, A> PersistentStore<S, A>
where
    S: Store,
    S::State: serde::Serialize + serde::de::DeserializeOwned,
    A: PersistenceAdapter + 'static,
{
    /// Save the current state to storage.
    pub async fn save(&self) -> PersistResult<()> {
        // Use get_untracked() since we're in an async context without reactive tracking
        let state = self.inner.state().get_untracked();
        let persisted = PersistedState::new(state, self.config.version);

        let data = serde_json::to_vec(&persisted)
            .map_err(|e| PersistError::Serialization(e.to_string()))?;

        self.adapter.save(&self.storage_key(), &data).await
    }

    /// Load state from storage.
    ///
    /// Returns `None` if no data is found.
    pub async fn load(&self) -> PersistResult<Option<S::State>> {
        let data = self.adapter.load(&self.storage_key()).await?;

        match data {
            Some(bytes) => {
                let persisted: PersistedState<S::State> = serde_json::from_slice(&bytes)
                    .map_err(|e| PersistError::Deserialization(e.to_string()))?;

                // Check version
                if persisted.version != self.config.version {
                    return Err(PersistError::VersionMismatch {
                        expected: self.config.version,
                        found: persisted.version,
                    });
                }

                Ok(Some(persisted.state))
            }
            None => Ok(None),
        }
    }

    /// Remove persisted state from storage.
    pub async fn remove(&self) -> PersistResult<()> {
        self.adapter.remove(&self.storage_key()).await
    }

    /// Check if persisted state exists.
    pub async fn exists(&self) -> PersistResult<bool> {
        let data = self.adapter.load(&self.storage_key()).await?;
        Ok(data.is_some())
    }
}

impl<S, A> Store for PersistentStore<S, A>
where
    S: Store,
    A: PersistenceAdapter + 'static,
{
    type State = S::State;

    fn state(&self) -> leptos::prelude::ReadSignal<Self::State> {
        self.inner.state()
    }

    fn id(&self) -> crate::store::StoreId {
        self.inner.id()
    }

    fn name(&self) -> &'static str {
        self.inner.name()
    }
}

impl<S, A> fmt::Debug for PersistentStore<S, A>
where
    S: Store + fmt::Debug,
    A: PersistenceAdapter + 'static,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PersistentStore")
            .field("inner", &self.inner)
            .field("storage_type", &self.adapter.storage_type())
            .field("key", &self.storage_key())
            .finish()
    }
}

// ============================================================================
// Web Storage Adapters (feature-gated)
// ============================================================================

/// LocalStorage adapter for browser environments.
///
/// This adapter uses the Web Storage API's localStorage, which persists
/// data across browser sessions.
///
/// # Feature
///
/// Requires the `persist-web` feature.
///
/// # Limitations
///
/// - Synchronous API (but wrapped as async for uniformity)
/// - ~5MB storage limit per origin
/// - String-only storage (data is base64 encoded)
#[cfg(feature = "persist-web")]
pub struct LocalStorageAdapter {
    _private: (),
}

#[cfg(feature = "persist-web")]
impl Default for LocalStorageAdapter {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(feature = "persist-web")]
impl LocalStorageAdapter {
    /// Create a new localStorage adapter.
    pub fn new() -> Self {
        Self { _private: () }
    }

    #[cfg(target_arch = "wasm32")]
    fn get_storage(&self) -> PersistResult<web_sys::Storage> {
        web_sys::window()
            .ok_or_else(|| PersistError::NotAvailable("No window object".to_string()))?
            .local_storage()
            .map_err(|_| PersistError::NotAvailable("localStorage not accessible".to_string()))?
            .ok_or_else(|| PersistError::NotAvailable("localStorage is null".to_string()))
    }
}

#[cfg(feature = "persist-web")]
impl PersistenceAdapter for LocalStorageAdapter {
    fn save<'a>(&'a self, key: &'a str, data: &'a [u8]) -> PersistFuture<'a, ()> {
        #[cfg(target_arch = "wasm32")]
        {
            let key = key.to_string();
            let data = data.to_vec();
            let storage_result = self.get_storage();

            Box::pin(async move {
                let storage = storage_result?;
                let encoded = base64_encode(&data);
                storage
                    .set_item(&key, &encoded)
                    .map_err(|_| PersistError::QuotaExceeded)?;
                Ok(())
            })
        }

        #[cfg(not(target_arch = "wasm32"))]
        {
            let _ = (key, data);
            Box::pin(async { Err(PersistError::NotAvailable("Not in browser".to_string())) })
        }
    }

    fn load<'a>(&'a self, key: &'a str) -> PersistFuture<'a, Option<Vec<u8>>> {
        #[cfg(target_arch = "wasm32")]
        {
            let key = key.to_string();
            let storage_result = self.get_storage();

            Box::pin(async move {
                let storage = storage_result?;
                match storage.get_item(&key) {
                    Ok(Some(encoded)) => {
                        let data = base64_decode(&encoded)
                            .map_err(|e| PersistError::Deserialization(e.to_string()))?;
                        Ok(Some(data))
                    }
                    Ok(None) => Ok(None),
                    Err(_) => Err(PersistError::Internal(
                        "Failed to read localStorage".to_string(),
                    )),
                }
            })
        }

        #[cfg(not(target_arch = "wasm32"))]
        {
            let _ = key;
            Box::pin(async { Err(PersistError::NotAvailable("Not in browser".to_string())) })
        }
    }

    fn remove<'a>(&'a self, key: &'a str) -> PersistFuture<'a, ()> {
        #[cfg(target_arch = "wasm32")]
        {
            let key = key.to_string();
            let storage_result = self.get_storage();

            Box::pin(async move {
                let storage = storage_result?;
                storage
                    .remove_item(&key)
                    .map_err(|_| PersistError::Internal("Failed to remove item".to_string()))?;
                Ok(())
            })
        }

        #[cfg(not(target_arch = "wasm32"))]
        {
            let _ = key;
            Box::pin(async { Err(PersistError::NotAvailable("Not in browser".to_string())) })
        }
    }

    fn storage_type(&self) -> StorageType {
        StorageType::LocalStorage
    }

    #[cfg(target_arch = "wasm32")]
    fn is_available(&self) -> bool {
        self.get_storage().is_ok()
    }

    #[cfg(not(target_arch = "wasm32"))]
    fn is_available(&self) -> bool {
        false
    }
}

/// SessionStorage adapter for browser environments.
///
/// This adapter uses the Web Storage API's sessionStorage, which persists
/// data only for the duration of the browser session.
///
/// # Feature
///
/// Requires the `persist-web` feature.
#[cfg(feature = "persist-web")]
pub struct SessionStorageAdapter {
    _private: (),
}

#[cfg(feature = "persist-web")]
impl Default for SessionStorageAdapter {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(feature = "persist-web")]
impl SessionStorageAdapter {
    /// Create a new sessionStorage adapter.
    pub fn new() -> Self {
        Self { _private: () }
    }

    #[cfg(target_arch = "wasm32")]
    fn get_storage(&self) -> PersistResult<web_sys::Storage> {
        web_sys::window()
            .ok_or_else(|| PersistError::NotAvailable("No window object".to_string()))?
            .session_storage()
            .map_err(|_| PersistError::NotAvailable("sessionStorage not accessible".to_string()))?
            .ok_or_else(|| PersistError::NotAvailable("sessionStorage is null".to_string()))
    }
}

#[cfg(feature = "persist-web")]
impl PersistenceAdapter for SessionStorageAdapter {
    fn save<'a>(&'a self, key: &'a str, data: &'a [u8]) -> PersistFuture<'a, ()> {
        #[cfg(target_arch = "wasm32")]
        {
            let key = key.to_string();
            let data = data.to_vec();
            let storage_result = self.get_storage();

            Box::pin(async move {
                let storage = storage_result?;
                let encoded = base64_encode(&data);
                storage
                    .set_item(&key, &encoded)
                    .map_err(|_| PersistError::QuotaExceeded)?;
                Ok(())
            })
        }

        #[cfg(not(target_arch = "wasm32"))]
        {
            let _ = (key, data);
            Box::pin(async { Err(PersistError::NotAvailable("Not in browser".to_string())) })
        }
    }

    fn load<'a>(&'a self, key: &'a str) -> PersistFuture<'a, Option<Vec<u8>>> {
        #[cfg(target_arch = "wasm32")]
        {
            let key = key.to_string();
            let storage_result = self.get_storage();

            Box::pin(async move {
                let storage = storage_result?;
                match storage.get_item(&key) {
                    Ok(Some(encoded)) => {
                        let data = base64_decode(&encoded)
                            .map_err(|e| PersistError::Deserialization(e.to_string()))?;
                        Ok(Some(data))
                    }
                    Ok(None) => Ok(None),
                    Err(_) => Err(PersistError::Internal(
                        "Failed to read sessionStorage".to_string(),
                    )),
                }
            })
        }

        #[cfg(not(target_arch = "wasm32"))]
        {
            let _ = key;
            Box::pin(async { Err(PersistError::NotAvailable("Not in browser".to_string())) })
        }
    }

    fn remove<'a>(&'a self, key: &'a str) -> PersistFuture<'a, ()> {
        #[cfg(target_arch = "wasm32")]
        {
            let key = key.to_string();
            let storage_result = self.get_storage();

            Box::pin(async move {
                let storage = storage_result?;
                storage
                    .remove_item(&key)
                    .map_err(|_| PersistError::Internal("Failed to remove item".to_string()))?;
                Ok(())
            })
        }

        #[cfg(not(target_arch = "wasm32"))]
        {
            let _ = key;
            Box::pin(async { Err(PersistError::NotAvailable("Not in browser".to_string())) })
        }
    }

    fn storage_type(&self) -> StorageType {
        StorageType::SessionStorage
    }

    #[cfg(target_arch = "wasm32")]
    fn is_available(&self) -> bool {
        self.get_storage().is_ok()
    }

    #[cfg(not(target_arch = "wasm32"))]
    fn is_available(&self) -> bool {
        false
    }
}

// ============================================================================
// IndexedDB Adapter (feature-gated)
// ============================================================================

/// IndexedDB adapter for larger persistent storage.
///
/// This adapter uses IndexedDB for storing larger amounts of data
/// with proper async support.
///
/// # Feature
///
/// Requires the `persist-idb` feature.
///
/// # Advantages
///
/// - Larger storage capacity (typically 50MB+)
/// - Proper async API
/// - Structured data support
/// - Transaction support
#[cfg(feature = "persist-idb")]
pub struct IndexedDbAdapter {
    _database_name: String,
    store_name: String,
}

#[cfg(feature = "persist-idb")]
impl IndexedDbAdapter {
    /// Create a new IndexedDB adapter.
    pub fn new(database_name: impl Into<String>) -> Self {
        Self {
            _database_name: database_name.into(),
            store_name: "store".to_string(),
        }
    }

    /// Set the object store name.
    pub fn with_store_name(mut self, name: impl Into<String>) -> Self {
        self.store_name = name.into();
        self
    }
}

#[cfg(feature = "persist-idb")]
impl PersistenceAdapter for IndexedDbAdapter {
    fn save<'a>(&'a self, key: &'a str, data: &'a [u8]) -> PersistFuture<'a, ()> {
        let _ = (key, data);
        // IndexedDB implementation would go here using idb crate
        Box::pin(async {
            Err(PersistError::NotAvailable(
                "IndexedDB not yet implemented".to_string(),
            ))
        })
    }

    fn load<'a>(&'a self, key: &'a str) -> PersistFuture<'a, Option<Vec<u8>>> {
        let _ = key;
        Box::pin(async {
            Err(PersistError::NotAvailable(
                "IndexedDB not yet implemented".to_string(),
            ))
        })
    }

    fn remove<'a>(&'a self, key: &'a str) -> PersistFuture<'a, ()> {
        let _ = key;
        Box::pin(async {
            Err(PersistError::NotAvailable(
                "IndexedDB not yet implemented".to_string(),
            ))
        })
    }

    fn storage_type(&self) -> StorageType {
        StorageType::IndexedDb
    }
}

// ============================================================================
// Server Sync Adapter (feature-gated)
// ============================================================================

/// Server sync adapter for SSR state persistence.
///
/// This adapter syncs state with a server endpoint, enabling state
/// persistence across server restarts and horizontal scaling.
///
/// # Feature
///
/// Requires the `persist-server` feature.
#[cfg(feature = "persist-server")]
pub struct ServerSyncAdapter {
    _endpoint: String,
}

#[cfg(feature = "persist-server")]
impl ServerSyncAdapter {
    /// Create a new server sync adapter.
    pub fn new(endpoint: impl Into<String>) -> Self {
        Self {
            _endpoint: endpoint.into(),
        }
    }
}

#[cfg(feature = "persist-server")]
impl PersistenceAdapter for ServerSyncAdapter {
    fn save<'a>(&'a self, key: &'a str, data: &'a [u8]) -> PersistFuture<'a, ()> {
        let _ = (key, data);
        Box::pin(async {
            Err(PersistError::NotAvailable(
                "Server sync not yet implemented".to_string(),
            ))
        })
    }

    fn load<'a>(&'a self, key: &'a str) -> PersistFuture<'a, Option<Vec<u8>>> {
        let _ = key;
        Box::pin(async {
            Err(PersistError::NotAvailable(
                "Server sync not yet implemented".to_string(),
            ))
        })
    }

    fn remove<'a>(&'a self, key: &'a str) -> PersistFuture<'a, ()> {
        let _ = key;
        Box::pin(async {
            Err(PersistError::NotAvailable(
                "Server sync not yet implemented".to_string(),
            ))
        })
    }

    fn storage_type(&self) -> StorageType {
        StorageType::Server
    }
}

// ============================================================================
// Helper Functions
// ============================================================================

/// Get current timestamp in milliseconds.
fn current_timestamp_ms() -> u64 {
    #[cfg(target_arch = "wasm32")]
    {
        js_sys::Date::now() as u64
    }
    #[cfg(not(target_arch = "wasm32"))]
    {
        use std::time::SystemTime;
        SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)
            .map(|d| d.as_millis() as u64)
            .unwrap_or(0)
    }
}

/// Base64 encode data.
#[cfg(feature = "persist-web")]
#[allow(dead_code)]
fn base64_encode(data: &[u8]) -> String {
    use std::io::Write;
    let mut encoder =
        base64::write::EncoderStringWriter::new(&base64::engine::general_purpose::STANDARD);
    encoder.write_all(data).unwrap();
    encoder.into_inner()
}

/// Base64 decode data.
#[cfg(feature = "persist-web")]
#[allow(dead_code)]
fn base64_decode(data: &str) -> Result<Vec<u8>, String> {
    use base64::Engine;
    base64::engine::general_purpose::STANDARD
        .decode(data)
        .map_err(|e| e.to_string())
}

// ============================================================================
// Derive macro for serialization (requires serde)
// ============================================================================

/// Implement Serialize and Deserialize for PersistedState.
#[cfg(any(feature = "hydrate", feature = "persist-web"))]
impl<State: serde::Serialize> serde::Serialize for PersistedState<State> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        use serde::ser::SerializeStruct;
        let mut s = serializer.serialize_struct("PersistedState", 3)?;
        s.serialize_field("state", &self.state)?;
        s.serialize_field("version", &self.version)?;
        s.serialize_field("saved_at", &self.saved_at)?;
        s.end()
    }
}

#[cfg(any(feature = "hydrate", feature = "persist-web"))]
impl<'de, State: serde::Deserialize<'de>> serde::Deserialize<'de> for PersistedState<State> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(serde::Deserialize)]
        struct PersistedStateHelper<S> {
            state: S,
            version: u32,
            saved_at: u64,
        }

        let helper = PersistedStateHelper::deserialize(deserializer)?;
        Ok(Self {
            state: helper.state,
            version: helper.version,
            saved_at: helper.saved_at,
        })
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use leptos::prelude::*;

    #[derive(Clone, Debug, Default, PartialEq)]
    struct TestState {
        count: i32,
    }

    #[derive(Clone)]
    struct TestStore {
        state: RwSignal<TestState>,
    }

    impl Store for TestStore {
        type State = TestState;

        fn state(&self) -> ReadSignal<Self::State> {
            self.state.read_only()
        }
    }

    #[test]
    fn test_persist_error_display() {
        assert!(
            PersistError::Serialization("test".to_string())
                .to_string()
                .contains("Serialization")
        );
        assert!(PersistError::QuotaExceeded.to_string().contains("quota"));
        assert!(
            PersistError::VersionMismatch {
                expected: 2,
                found: 1
            }
            .to_string()
            .contains("expected 2")
        );
    }

    #[test]
    fn test_storage_type_display() {
        assert_eq!(StorageType::Memory.to_string(), "Memory");
        assert_eq!(StorageType::LocalStorage.to_string(), "LocalStorage");
        assert_eq!(StorageType::IndexedDb.to_string(), "IndexedDB");
    }

    #[test]
    fn test_memory_adapter() {
        let adapter = MemoryAdapter::new();
        assert!(adapter.is_empty());
        assert_eq!(adapter.storage_type(), StorageType::Memory);
    }

    #[tokio::test]
    async fn test_memory_adapter_operations() {
        let adapter = MemoryAdapter::new();

        // Save
        adapter.save("key1", b"hello").await.unwrap();
        assert_eq!(adapter.len(), 1);

        // Load
        let data = adapter.load("key1").await.unwrap();
        assert_eq!(data, Some(b"hello".to_vec()));

        // Load non-existent
        let data = adapter.load("key2").await.unwrap();
        assert!(data.is_none());

        // Remove
        adapter.remove("key1").await.unwrap();
        assert!(adapter.is_empty());

        // Keys
        adapter.save("a", b"1").await.unwrap();
        adapter.save("b", b"2").await.unwrap();
        let keys = adapter.keys().await.unwrap();
        assert_eq!(keys.len(), 2);

        // Clear
        adapter.clear().await.unwrap();
        assert!(adapter.is_empty());
    }

    #[test]
    fn test_persist_config() {
        let config = PersistConfig::new("my_store");
        assert_eq!(config.key, "my_store");
        assert_eq!(config.full_key(), "leptos_store_my_store");
    }

    #[test]
    fn test_storage_capacity() {
        let unknown = StorageCapacity::unknown();
        assert!(unknown.total.is_none());

        let known = StorageCapacity::known(1000, 300);
        assert_eq!(known.total, Some(1000));
        assert_eq!(known.used, Some(300));
        assert_eq!(known.available, Some(700));
    }

    #[test]
    fn test_persistent_store_config() {
        let store = TestStore {
            state: RwSignal::new(TestState::default()),
        };

        let persistent = PersistentStore::new(store, MemoryAdapter::new())
            .with_key("test")
            .with_debounce(500)
            .with_version(2)
            .with_auto_save(false);

        assert_eq!(persistent.config().key, "test");
        assert_eq!(persistent.config().debounce_ms, 500);
        assert_eq!(persistent.config().version, 2);
        assert!(!persistent.config().auto_save);
    }
}