leptos-store 0.10.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
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
// SPDX-License-Identifier: Apache-2.0
// Copyright 2026 nyvorin

//! Middleware system for store actions and mutations.
//!
//! This module provides both an interceptor pattern (middleware chain) and
//! an event bus pattern for observing store operations.
//!
//! # Interceptor Pattern
//!
//! Middleware can intercept mutations and actions before and after execution:
//!
//! ```rust
//! # use leptos_store::store::Store;
//! use leptos_store::middleware::{Middleware, MiddlewareContext, MiddlewareResult};
//!
//! struct LoggingMiddleware;
//!
//! impl<S: Store> Middleware<S> for LoggingMiddleware {
//!     fn before_mutate(&self, ctx: &MiddlewareContext<S>) -> MiddlewareResult {
//!         println!("Before mutation: {}", ctx.mutation_name());
//!         MiddlewareResult::Continue
//!     }
//! }
//! ```
//!
//! # Event Bus Pattern
//!
//! Subscribe to store events for observation without affecting control flow:
//!
//! ```rust
//! use leptos_store::middleware::{EventSubscriber, StoreEvent};
//!
//! # fn record_metric(_name: &str, _duration_ms: u64) {}
//! struct MetricsSubscriber;
//!
//! impl EventSubscriber for MetricsSubscriber {
//!     fn on_event(&self, event: &StoreEvent) {
//!         match event {
//!             StoreEvent::MutationCompleted { name, duration_ms, .. } => {
//!                 record_metric(name, *duration_ms);
//!             }
//!             _ => {}
//!         }
//!     }
//! }
//! ```

use crate::store::{Store, StoreError, StoreId};
use leptos::prelude::Get;
use std::any::TypeId;
use std::fmt;
use std::sync::{Arc, RwLock};
use std::time::Duration;
use thiserror::Error;

// ============================================================================
// Cross-platform Timing
// ============================================================================

/// A cross-platform instant that works in both native and WASM.
#[derive(Clone, Copy, Debug)]
pub struct CrossInstant {
    #[cfg(target_arch = "wasm32")]
    millis: f64,
    #[cfg(not(target_arch = "wasm32"))]
    instant: std::time::Instant,
}

impl CrossInstant {
    /// Get the current instant.
    pub fn now() -> Self {
        #[cfg(target_arch = "wasm32")]
        {
            let millis = js_sys::Date::now();
            Self { millis }
        }
        #[cfg(not(target_arch = "wasm32"))]
        {
            Self {
                instant: std::time::Instant::now(),
            }
        }
    }

    /// Get the duration since this instant was created.
    pub fn elapsed(&self) -> Duration {
        #[cfg(target_arch = "wasm32")]
        {
            let now = js_sys::Date::now();
            let elapsed_ms = now - self.millis;
            Duration::from_millis(elapsed_ms.max(0.0) as u64)
        }
        #[cfg(not(target_arch = "wasm32"))]
        {
            self.instant.elapsed()
        }
    }
}

// ============================================================================
// Middleware Errors
// ============================================================================

/// Errors that can occur during middleware execution.
#[derive(Debug, Error, Clone)]
pub enum MiddlewareError {
    /// Middleware rejected the operation.
    #[error("Middleware rejected: {0}")]
    Rejected(String),

    /// Middleware validation failed.
    #[error("Validation failed: {0}")]
    ValidationFailed(String),

    /// Middleware timed out.
    #[error("Middleware timed out after {0}ms")]
    Timeout(u64),

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

// ============================================================================
// Middleware Result
// ============================================================================

/// Result of middleware execution that controls the pipeline flow.
#[derive(Debug, Clone, Default)]
pub enum MiddlewareResult {
    /// Continue to the next middleware or operation.
    #[default]
    Continue,
    /// Skip remaining middleware but execute the operation.
    Skip,
    /// Abort the entire operation.
    Abort(MiddlewareError),
    /// Transform and continue (for advanced use cases).
    Transform,
}

impl MiddlewareResult {
    /// Check if the result allows continuation.
    pub fn should_continue(&self) -> bool {
        matches!(self, Self::Continue | Self::Transform)
    }

    /// Check if the result is an abort.
    pub fn is_abort(&self) -> bool {
        matches!(self, Self::Abort(_))
    }

    /// Get the error if this is an abort result.
    pub fn error(&self) -> Option<&MiddlewareError> {
        match self {
            Self::Abort(e) => Some(e),
            _ => None,
        }
    }
}

// ============================================================================
// Mutation Result
// ============================================================================

/// Result of a mutation operation.
#[derive(Debug, Clone)]
pub struct MutationResult {
    /// Whether the mutation succeeded.
    pub success: bool,
    /// Duration of the mutation.
    pub duration: Duration,
    /// Error message if failed.
    pub error: Option<String>,
}

impl MutationResult {
    /// Create a successful mutation result.
    pub fn success(duration: Duration) -> Self {
        Self {
            success: true,
            duration,
            error: None,
        }
    }

    /// Create a failed mutation result.
    pub fn failure(duration: Duration, error: impl Into<String>) -> Self {
        Self {
            success: false,
            duration,
            error: Some(error.into()),
        }
    }
}

/// Result of an action operation.
#[derive(Debug, Clone)]
pub struct ActionResult {
    /// Whether the action succeeded.
    pub success: bool,
    /// Duration of the action.
    pub duration: Duration,
    /// Error message if failed.
    pub error: Option<String>,
    /// Output type name (for debugging).
    pub output_type: Option<&'static str>,
}

impl ActionResult {
    /// Create a successful action result.
    pub fn success(duration: Duration) -> Self {
        Self {
            success: true,
            duration,
            error: None,
            output_type: None,
        }
    }

    /// Create a successful action result with output type.
    pub fn success_with_output(duration: Duration, output_type: &'static str) -> Self {
        Self {
            success: true,
            duration,
            error: None,
            output_type: Some(output_type),
        }
    }

    /// Create a failed action result.
    pub fn failure(duration: Duration, error: impl Into<String>) -> Self {
        Self {
            success: false,
            duration,
            error: Some(error.into()),
            output_type: None,
        }
    }
}

// ============================================================================
// Middleware Context
// ============================================================================

/// Context provided to middleware during mutation interception.
pub struct MiddlewareContext<'a, S: Store> {
    store: &'a S,
    mutation_name: &'static str,
    timestamp: CrossInstant,
    metadata: ContextMetadata,
}

impl<'a, S: Store> MiddlewareContext<'a, S> {
    /// Create a new middleware context.
    pub fn new(store: &'a S, mutation_name: &'static str) -> Self {
        Self {
            store,
            mutation_name,
            timestamp: CrossInstant::now(),
            metadata: ContextMetadata::default(),
        }
    }

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

    /// Get the current state (read-only).
    pub fn state(&self) -> S::State {
        self.store.state().get()
    }

    /// Get the mutation name.
    pub fn mutation_name(&self) -> &'static str {
        self.mutation_name
    }

    /// Get the timestamp when this context was created.
    pub fn timestamp(&self) -> CrossInstant {
        self.timestamp
    }

    /// Get the elapsed time since context creation.
    pub fn elapsed(&self) -> Duration {
        self.timestamp.elapsed()
    }

    /// Get the store's unique identifier.
    pub fn store_id(&self) -> StoreId {
        self.store.id()
    }

    /// Get the store's name.
    pub fn store_name(&self) -> &'static str {
        self.store.name()
    }

    /// Get mutable access to metadata.
    pub fn metadata_mut(&mut self) -> &mut ContextMetadata {
        &mut self.metadata
    }

    /// Get read-only access to metadata.
    pub fn metadata(&self) -> &ContextMetadata {
        &self.metadata
    }
}

/// Context provided to middleware during action interception.
pub struct ActionContext<'a, S: Store> {
    store: &'a S,
    action_type: TypeId,
    action_name: &'static str,
    timestamp: CrossInstant,
    metadata: ContextMetadata,
}

impl<'a, S: Store> ActionContext<'a, S> {
    /// Create a new action context.
    pub fn new(store: &'a S, action_type: TypeId, action_name: &'static str) -> Self {
        Self {
            store,
            action_type,
            action_name,
            timestamp: CrossInstant::now(),
            metadata: ContextMetadata::default(),
        }
    }

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

    /// Get the current state (read-only).
    pub fn state(&self) -> S::State {
        self.store.state().get()
    }

    /// Get the action type ID.
    pub fn action_type(&self) -> TypeId {
        self.action_type
    }

    /// Get the action name.
    pub fn action_name(&self) -> &'static str {
        self.action_name
    }

    /// Get the timestamp when this context was created.
    pub fn timestamp(&self) -> CrossInstant {
        self.timestamp
    }

    /// Get the elapsed time since context creation.
    pub fn elapsed(&self) -> Duration {
        self.timestamp.elapsed()
    }

    /// Get the store's unique identifier.
    pub fn store_id(&self) -> StoreId {
        self.store.id()
    }

    /// Get the store's name.
    pub fn store_name(&self) -> &'static str {
        self.store.name()
    }

    /// Get mutable access to metadata.
    pub fn metadata_mut(&mut self) -> &mut ContextMetadata {
        &mut self.metadata
    }

    /// Get read-only access to metadata.
    pub fn metadata(&self) -> &ContextMetadata {
        &self.metadata
    }
}

/// Metadata that can be attached to middleware contexts.
#[derive(Debug, Clone, Default)]
pub struct ContextMetadata {
    /// User-defined tags for filtering/routing.
    pub tags: Vec<String>,
    /// Correlation ID for distributed tracing.
    pub correlation_id: Option<String>,
    /// Parent span ID for tracing.
    pub parent_span_id: Option<String>,
    /// Custom key-value pairs.
    pub custom: std::collections::HashMap<String, String>,
}

impl ContextMetadata {
    /// Create new empty metadata.
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a tag.
    pub fn with_tag(mut self, tag: impl Into<String>) -> Self {
        self.tags.push(tag.into());
        self
    }

    /// Set correlation ID.
    pub fn with_correlation_id(mut self, id: impl Into<String>) -> Self {
        self.correlation_id = Some(id.into());
        self
    }

    /// Add a custom key-value pair.
    pub fn with_custom(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.custom.insert(key.into(), value.into());
        self
    }
}

// ============================================================================
// Middleware Trait
// ============================================================================

/// Trait for middleware that intercepts store operations.
///
/// Middleware can observe and modify the execution of mutations and actions.
/// Each method returns a `MiddlewareResult` that controls whether the
/// operation should continue, skip, or abort.
///
/// # Example
///
/// ```rust
/// use leptos_store::store::Store;
/// use leptos_store::middleware::{Middleware, MiddlewareContext, MiddlewareResult, MutationResult};
///
/// struct ValidationMiddleware;
///
/// impl<S: Store> Middleware<S> for ValidationMiddleware {
///     fn before_mutate(&self, ctx: &MiddlewareContext<S>) -> MiddlewareResult {
///         // Validate state before mutation
///         MiddlewareResult::Continue
///     }
///
///     fn after_mutate(&self, ctx: &MiddlewareContext<S>, result: &MutationResult) {
///         if !result.success {
///             eprintln!("Mutation failed: {:?}", result.error);
///         }
///     }
/// }
/// ```
pub trait Middleware<S: Store>: Send + Sync {
    /// Called before a mutation is executed.
    ///
    /// Return `MiddlewareResult::Continue` to proceed, or `Abort` to cancel.
    fn before_mutate(&self, _ctx: &MiddlewareContext<S>) -> MiddlewareResult {
        MiddlewareResult::Continue
    }

    /// Called after a mutation is executed.
    fn after_mutate(&self, _ctx: &MiddlewareContext<S>, _result: &MutationResult) {}

    /// Called before an action is executed.
    ///
    /// Return `MiddlewareResult::Continue` to proceed, or `Abort` to cancel.
    fn before_action(&self, _ctx: &ActionContext<S>) -> MiddlewareResult {
        MiddlewareResult::Continue
    }

    /// Called after an action is executed.
    fn after_action(&self, _ctx: &ActionContext<S>, _result: &ActionResult) {}

    /// Get the middleware name for debugging.
    fn name(&self) -> &'static str {
        std::any::type_name::<Self>()
    }

    /// Get the middleware priority (higher = runs first).
    fn priority(&self) -> i32 {
        0
    }
}

// ============================================================================
// Middleware Chain
// ============================================================================

/// A chain of middleware that processes operations in order.
///
/// Middleware is executed in priority order (highest first) for `before_*` hooks
/// and reverse order for `after_*` hooks.
pub struct MiddlewareChain<S: Store> {
    middleware: Vec<Arc<dyn Middleware<S>>>,
    sorted: bool,
}

impl<S: Store> Default for MiddlewareChain<S> {
    fn default() -> Self {
        Self::new()
    }
}

impl<S: Store> MiddlewareChain<S> {
    /// Create a new empty middleware chain.
    pub fn new() -> Self {
        Self {
            middleware: Vec::new(),
            sorted: true,
        }
    }

    /// Add middleware to the chain.
    pub fn add<M: Middleware<S> + 'static>(&mut self, middleware: M) {
        self.middleware.push(Arc::new(middleware));
        self.sorted = false;
    }

    /// Add middleware wrapped in Arc.
    pub fn add_arc(&mut self, middleware: Arc<dyn Middleware<S>>) {
        self.middleware.push(middleware);
        self.sorted = false;
    }

    /// Get the number of middleware in the chain.
    pub fn len(&self) -> usize {
        self.middleware.len()
    }

    /// Check if the chain is empty.
    pub fn is_empty(&self) -> bool {
        self.middleware.is_empty()
    }

    /// Sort middleware by priority (called automatically when needed).
    fn ensure_sorted(&mut self) {
        if !self.sorted {
            self.middleware
                .sort_by_key(|b| std::cmp::Reverse(b.priority()));
            self.sorted = true;
        }
    }

    /// Execute before_mutate on all middleware.
    ///
    /// Returns the first `Abort` result, or `Continue` if all pass.
    pub fn before_mutate(&mut self, ctx: &MiddlewareContext<S>) -> MiddlewareResult {
        self.ensure_sorted();

        for m in &self.middleware {
            let result = m.before_mutate(ctx);
            if result.is_abort() {
                return result;
            }
            if matches!(result, MiddlewareResult::Skip) {
                break;
            }
        }

        MiddlewareResult::Continue
    }

    /// Execute after_mutate on all middleware (reverse order).
    pub fn after_mutate(&mut self, ctx: &MiddlewareContext<S>, result: &MutationResult) {
        self.ensure_sorted();

        for m in self.middleware.iter().rev() {
            m.after_mutate(ctx, result);
        }
    }

    /// Execute before_action on all middleware.
    pub fn before_action(&mut self, ctx: &ActionContext<S>) -> MiddlewareResult {
        self.ensure_sorted();

        for m in &self.middleware {
            let result = m.before_action(ctx);
            if result.is_abort() {
                return result;
            }
            if matches!(result, MiddlewareResult::Skip) {
                break;
            }
        }

        MiddlewareResult::Continue
    }

    /// Execute after_action on all middleware (reverse order).
    pub fn after_action(&mut self, ctx: &ActionContext<S>, result: &ActionResult) {
        self.ensure_sorted();

        for m in self.middleware.iter().rev() {
            m.after_action(ctx, result);
        }
    }
}

impl<S: Store> fmt::Debug for MiddlewareChain<S> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("MiddlewareChain")
            .field("count", &self.middleware.len())
            .field(
                "middleware",
                &self.middleware.iter().map(|m| m.name()).collect::<Vec<_>>(),
            )
            .finish()
    }
}

// ============================================================================
// Event Bus
// ============================================================================

/// Events emitted by stores for observation.
#[derive(Debug, Clone)]
pub enum StoreEvent {
    /// State has changed.
    StateChanged {
        /// The store that changed.
        store_id: StoreId,
        /// Store name for debugging.
        store_name: &'static str,
        /// Timestamp of the change (milliseconds since epoch).
        timestamp: u64,
    },

    /// A mutation has started.
    MutationStarted {
        /// The store being mutated.
        store_id: StoreId,
        /// Name of the mutation.
        name: &'static str,
        /// Timestamp when started.
        timestamp: u64,
    },

    /// A mutation has completed.
    MutationCompleted {
        /// The store that was mutated.
        store_id: StoreId,
        /// Name of the mutation.
        name: &'static str,
        /// Duration in milliseconds.
        duration_ms: u64,
        /// Whether it succeeded.
        success: bool,
    },

    /// An action has been dispatched.
    ActionDispatched {
        /// The store handling the action.
        store_id: StoreId,
        /// Type ID of the action.
        action_type: TypeId,
        /// Name of the action.
        action_name: &'static str,
        /// Timestamp when dispatched.
        timestamp: u64,
    },

    /// An action has completed.
    ActionCompleted {
        /// The store that handled the action.
        store_id: StoreId,
        /// Name of the action.
        action_name: &'static str,
        /// Duration in milliseconds.
        duration_ms: u64,
        /// Whether it succeeded.
        success: bool,
    },

    /// An error occurred.
    Error {
        /// The store where the error occurred.
        store_id: StoreId,
        /// Error description.
        message: String,
        /// Source of the error.
        source: ErrorSource,
    },

    /// A cache invalidation was triggered.
    ///
    /// Emitted by [`StoreCoordinator::invalidate_on_change`](crate::coordination::StoreCoordinator::invalidate_on_change)
    /// when a source store mutates, signaling that dependent caches or
    /// derived data should be refreshed.
    CacheInvalidated {
        /// The store that triggered the invalidation.
        source_store_id: StoreId,
        /// Optional scope label to narrow which caches to invalidate
        /// (e.g. `"pricing"`, `"inventory"`). `None` means all caches.
        scope: Option<&'static str>,
        /// Timestamp in milliseconds since epoch.
        timestamp: u64,
    },
}

/// Source of an error event.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ErrorSource {
    /// Error occurred during mutation.
    Mutation,
    /// Error occurred during action.
    Action,
    /// Error occurred in middleware.
    Middleware,
    /// Error occurred during persistence.
    Persistence,
    /// Error occurred during cache invalidation.
    Invalidation,
    /// Unknown or other source.
    Unknown,
}

/// Trait for subscribers that receive store events.
pub trait EventSubscriber: Send + Sync {
    /// Called when a store event occurs.
    fn on_event(&self, event: &StoreEvent);

    /// Get the subscriber name for debugging.
    fn name(&self) -> &'static str {
        std::any::type_name::<Self>()
    }

    /// Filter events this subscriber is interested in.
    ///
    /// Return `true` to receive the event, `false` to skip it.
    fn filter(&self, _event: &StoreEvent) -> bool {
        true
    }
}

/// An event bus for distributing store events to subscribers.
pub struct EventBus {
    subscribers: RwLock<Vec<Arc<dyn EventSubscriber>>>,
}

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

impl EventBus {
    /// Create a new event bus.
    pub fn new() -> Self {
        Self {
            subscribers: RwLock::new(Vec::new()),
        }
    }

    /// Subscribe to events.
    pub fn subscribe<S: EventSubscriber + 'static>(&self, subscriber: S) {
        if let Ok(mut subs) = self.subscribers.write() {
            subs.push(Arc::new(subscriber));
        }
    }

    /// Subscribe with an Arc.
    pub fn subscribe_arc(&self, subscriber: Arc<dyn EventSubscriber>) {
        if let Ok(mut subs) = self.subscribers.write() {
            subs.push(subscriber);
        }
    }

    /// Emit an event to all subscribers.
    pub fn emit(&self, event: StoreEvent) {
        if let Ok(subs) = self.subscribers.read() {
            for sub in subs.iter() {
                if sub.filter(&event) {
                    sub.on_event(&event);
                }
            }
        }
    }

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

    /// Clear all subscribers.
    pub fn clear(&self) {
        if let Ok(mut subs) = self.subscribers.write() {
            subs.clear();
        }
    }
}

impl fmt::Debug for EventBus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let count = self.subscriber_count();
        f.debug_struct("EventBus")
            .field("subscriber_count", &count)
            .finish()
    }
}

// ============================================================================
// Middleware-enabled Store Wrapper
// ============================================================================

/// A store wrapper that enables middleware support.
///
/// This wrapper adds middleware hooks around mutations and actions
/// while maintaining full compatibility with the underlying store.
pub struct MiddlewareStore<S: Store> {
    inner: S,
    middleware: Arc<RwLock<MiddlewareChain<S>>>,
    event_bus: Arc<EventBus>,
}

impl<S: Store> Clone for MiddlewareStore<S> {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
            middleware: Arc::clone(&self.middleware),
            event_bus: Arc::clone(&self.event_bus),
        }
    }
}

impl<S: Store> MiddlewareStore<S> {
    /// Create a new middleware-enabled store.
    pub fn new(store: S) -> Self {
        Self {
            inner: store,
            middleware: Arc::new(RwLock::new(MiddlewareChain::new())),
            event_bus: Arc::new(EventBus::new()),
        }
    }

    /// Create with a shared event bus.
    pub fn with_event_bus(store: S, event_bus: Arc<EventBus>) -> Self {
        Self {
            inner: store,
            middleware: Arc::new(RwLock::new(MiddlewareChain::new())),
            event_bus,
        }
    }

    /// 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
    }

    /// Add middleware to this store.
    pub fn add_middleware<M: Middleware<S> + 'static>(&self, middleware: M) {
        if let Ok(mut chain) = self.middleware.write() {
            chain.add(middleware);
        }
    }

    /// Subscribe to events from this store.
    pub fn subscribe<E: EventSubscriber + 'static>(&self, subscriber: E) {
        self.event_bus.subscribe(subscriber);
    }

    /// Get the event bus.
    pub fn event_bus(&self) -> &Arc<EventBus> {
        &self.event_bus
    }

    /// Execute a mutation with middleware hooks.
    ///
    /// Returns `Ok(())` if the mutation succeeded, or an error if
    /// middleware aborted or the mutation failed.
    pub fn mutate<F>(&self, mutation_name: &'static str, mutate_fn: F) -> Result<(), StoreError>
    where
        F: FnOnce(),
    {
        let ctx = MiddlewareContext::new(&self.inner, mutation_name);
        let start = CrossInstant::now();

        // Emit mutation started event
        self.event_bus.emit(StoreEvent::MutationStarted {
            store_id: self.inner.id(),
            name: mutation_name,
            timestamp: current_timestamp_ms(),
        });

        // Run before_mutate middleware
        let before_result = if let Ok(mut chain) = self.middleware.write() {
            chain.before_mutate(&ctx)
        } else {
            MiddlewareResult::Continue
        };

        if let MiddlewareResult::Abort(err) = before_result {
            let result = MutationResult::failure(start.elapsed(), err.to_string());
            if let Ok(mut chain) = self.middleware.write() {
                chain.after_mutate(&ctx, &result);
            }
            self.event_bus.emit(StoreEvent::MutationCompleted {
                store_id: self.inner.id(),
                name: mutation_name,
                duration_ms: start.elapsed().as_millis() as u64,
                success: false,
            });
            return Err(StoreError::MutationFailed(err.to_string()));
        }

        // Execute the mutation
        mutate_fn();

        let result = MutationResult::success(start.elapsed());

        // Run after_mutate middleware
        if let Ok(mut chain) = self.middleware.write() {
            chain.after_mutate(&ctx, &result);
        }

        // Emit completion event
        self.event_bus.emit(StoreEvent::MutationCompleted {
            store_id: self.inner.id(),
            name: mutation_name,
            duration_ms: start.elapsed().as_millis() as u64,
            success: true,
        });

        Ok(())
    }

    /// Execute an action with middleware hooks.
    pub fn dispatch<F, R>(
        &self,
        action_name: &'static str,
        action_type: TypeId,
        action_fn: F,
    ) -> Result<R, StoreError>
    where
        F: FnOnce() -> R,
    {
        let ctx = ActionContext::new(&self.inner, action_type, action_name);
        let start = CrossInstant::now();

        // Emit action dispatched event
        self.event_bus.emit(StoreEvent::ActionDispatched {
            store_id: self.inner.id(),
            action_type,
            action_name,
            timestamp: current_timestamp_ms(),
        });

        // Run before_action middleware
        let before_result = if let Ok(mut chain) = self.middleware.write() {
            chain.before_action(&ctx)
        } else {
            MiddlewareResult::Continue
        };

        if let MiddlewareResult::Abort(err) = before_result {
            let result = ActionResult::failure(start.elapsed(), err.to_string());
            if let Ok(mut chain) = self.middleware.write() {
                chain.after_action(&ctx, &result);
            }
            self.event_bus.emit(StoreEvent::ActionCompleted {
                store_id: self.inner.id(),
                action_name,
                duration_ms: start.elapsed().as_millis() as u64,
                success: false,
            });
            return Err(StoreError::MutationFailed(err.to_string()));
        }

        // Execute the action
        let output = action_fn();

        let result = ActionResult::success_with_output(start.elapsed(), std::any::type_name::<R>());

        // Run after_action middleware
        if let Ok(mut chain) = self.middleware.write() {
            chain.after_action(&ctx, &result);
        }

        // Emit completion event
        self.event_bus.emit(StoreEvent::ActionCompleted {
            store_id: self.inner.id(),
            action_name,
            duration_ms: start.elapsed().as_millis() as u64,
            success: true,
        });

        Ok(output)
    }
}

impl<S: Store> Store for MiddlewareStore<S> {
    type State = S::State;

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

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

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

// ============================================================================
// Built-in Middleware: Logging
// ============================================================================

/// Log level for the logging middleware.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum LogLevel {
    /// Trace level - most verbose.
    Trace,
    /// Debug level.
    Debug,
    /// Info level - default.
    #[default]
    Info,
    /// Warn level.
    Warn,
    /// Error level - least verbose.
    Error,
    /// No logging.
    Off,
}

/// Configuration for the logging middleware.
#[derive(Debug, Clone)]
pub struct LoggingConfig {
    /// Minimum log level to emit.
    pub level: LogLevel,
    /// Whether to log state before mutations.
    pub log_state_before: bool,
    /// Whether to log state after mutations.
    pub log_state_after: bool,
    /// Whether to log timing information.
    pub log_timing: bool,
    /// Prefix for log messages.
    pub prefix: &'static str,
}

impl Default for LoggingConfig {
    fn default() -> Self {
        Self {
            level: LogLevel::Info,
            log_state_before: false,
            log_state_after: false,
            log_timing: true,
            prefix: "[Store]",
        }
    }
}

/// Logging middleware that outputs store operations to the console.
///
/// # Example
///
/// ```rust
/// # use leptos::prelude::{RwSignal, ReadSignal};
/// # use leptos_store::store::Store;
/// use leptos_store::middleware::{MiddlewareStore, LoggingMiddleware};
/// # #[derive(Clone, Debug, Default)]
/// # struct MyState;
/// # #[derive(Clone)]
/// # struct MyStore { state: RwSignal<MyState> }
/// # impl Store for MyStore {
/// #     type State = MyState;
/// #     fn state(&self) -> ReadSignal<Self::State> { self.state.read_only() }
/// # }
/// # let my_store = MyStore { state: RwSignal::new(MyState::default()) };
/// let store = MiddlewareStore::new(my_store);
/// store.add_middleware(LoggingMiddleware::new());
/// ```
pub struct LoggingMiddleware {
    config: LoggingConfig,
}

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

impl LoggingMiddleware {
    /// Create a new logging middleware with default configuration.
    pub fn new() -> Self {
        Self {
            config: LoggingConfig::default(),
        }
    }

    /// Create with custom configuration.
    pub fn with_config(config: LoggingConfig) -> Self {
        Self { config }
    }

    /// Set the log level.
    pub fn with_level(mut self, level: LogLevel) -> Self {
        self.config.level = level;
        self
    }

    /// Enable state logging before mutations.
    pub fn log_state_before(mut self) -> Self {
        self.config.log_state_before = true;
        self
    }

    /// Enable state logging after mutations.
    pub fn log_state_after(mut self) -> Self {
        self.config.log_state_after = true;
        self
    }

    /// Set a custom prefix.
    pub fn with_prefix(mut self, prefix: &'static str) -> Self {
        self.config.prefix = prefix;
        self
    }

    fn should_log(&self) -> bool {
        self.config.level != LogLevel::Off
    }

    fn log(&self, level: LogLevel, message: &str) {
        if self.config.level == LogLevel::Off {
            return;
        }

        // Only log if the message level is >= configured level
        let should_emit = match (level, self.config.level) {
            (LogLevel::Off, _) => false,
            (_, LogLevel::Off) => false,
            (LogLevel::Error, _) => true,
            (LogLevel::Warn, LogLevel::Error) => false,
            (LogLevel::Warn, _) => true,
            (LogLevel::Info, LogLevel::Error | LogLevel::Warn) => false,
            (LogLevel::Info, _) => true,
            (LogLevel::Debug, LogLevel::Error | LogLevel::Warn | LogLevel::Info) => false,
            (LogLevel::Debug, _) => true,
            (LogLevel::Trace, LogLevel::Trace) => true,
            (LogLevel::Trace, _) => false,
        };

        if should_emit {
            // Use leptos logging which works in both WASM and native
            match level {
                LogLevel::Error => leptos::logging::error!("{} {}", self.config.prefix, message),
                LogLevel::Warn => leptos::logging::warn!("{} {}", self.config.prefix, message),
                LogLevel::Debug => {
                    leptos::logging::debug_warn!("{} {}", self.config.prefix, message)
                }
                _ => leptos::logging::log!("{} {}", self.config.prefix, message),
            }
        }
    }
}

impl<S: Store> Middleware<S> for LoggingMiddleware {
    fn before_mutate(&self, ctx: &MiddlewareContext<S>) -> MiddlewareResult {
        if self.should_log() {
            self.log(
                LogLevel::Info,
                &format!("Mutation started: {}", ctx.mutation_name()),
            );

            if self.config.log_state_before {
                self.log(
                    LogLevel::Debug,
                    &format!("State before: (store: {})", ctx.store_name()),
                );
            }
        }
        MiddlewareResult::Continue
    }

    fn after_mutate(&self, ctx: &MiddlewareContext<S>, result: &MutationResult) {
        if self.should_log() {
            let status = if result.success {
                "completed"
            } else {
                "failed"
            };

            if self.config.log_timing {
                self.log(
                    if result.success {
                        LogLevel::Info
                    } else {
                        LogLevel::Error
                    },
                    &format!(
                        "Mutation {}: {} ({:?})",
                        status,
                        ctx.mutation_name(),
                        result.duration
                    ),
                );
            } else {
                self.log(
                    if result.success {
                        LogLevel::Info
                    } else {
                        LogLevel::Error
                    },
                    &format!("Mutation {}: {}", status, ctx.mutation_name()),
                );
            }

            if !result.success
                && let Some(ref err) = result.error
            {
                self.log(LogLevel::Error, &format!("Error: {}", err));
            }

            if self.config.log_state_after {
                self.log(
                    LogLevel::Debug,
                    &format!("State after: (store: {})", ctx.store_name()),
                );
            }
        }
    }

    fn before_action(&self, ctx: &ActionContext<S>) -> MiddlewareResult {
        if self.should_log() {
            self.log(
                LogLevel::Info,
                &format!("Action dispatched: {}", ctx.action_name()),
            );
        }
        MiddlewareResult::Continue
    }

    fn after_action(&self, ctx: &ActionContext<S>, result: &ActionResult) {
        if self.should_log() {
            let status = if result.success {
                "completed"
            } else {
                "failed"
            };

            if self.config.log_timing {
                self.log(
                    if result.success {
                        LogLevel::Info
                    } else {
                        LogLevel::Error
                    },
                    &format!(
                        "Action {}: {} ({:?})",
                        status,
                        ctx.action_name(),
                        result.duration
                    ),
                );
            } else {
                self.log(
                    if result.success {
                        LogLevel::Info
                    } else {
                        LogLevel::Error
                    },
                    &format!("Action {}: {}", status, ctx.action_name()),
                );
            }

            if !result.success
                && let Some(ref err) = result.error
            {
                self.log(LogLevel::Error, &format!("Error: {}", err));
            }
        }
    }

    fn name(&self) -> &'static str {
        "LoggingMiddleware"
    }

    fn priority(&self) -> i32 {
        -100 // Run last in before hooks, first in after hooks
    }
}

// ============================================================================
// Built-in Middleware: Timing
// ============================================================================

/// Timing middleware that tracks operation durations.
///
/// This middleware emits timing events that can be used for performance
/// monitoring and debugging.
pub struct TimingMiddleware {
    /// Threshold in milliseconds above which to warn.
    warn_threshold_ms: u64,
    /// Threshold in milliseconds above which to error.
    error_threshold_ms: u64,
}

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

impl TimingMiddleware {
    /// Create a new timing middleware with default thresholds.
    pub fn new() -> Self {
        Self {
            warn_threshold_ms: 100,
            error_threshold_ms: 1000,
        }
    }

    /// Set the warning threshold.
    pub fn with_warn_threshold(mut self, ms: u64) -> Self {
        self.warn_threshold_ms = ms;
        self
    }

    /// Set the error threshold.
    pub fn with_error_threshold(mut self, ms: u64) -> Self {
        self.error_threshold_ms = ms;
        self
    }
}

impl<S: Store> Middleware<S> for TimingMiddleware {
    fn after_mutate(&self, ctx: &MiddlewareContext<S>, result: &MutationResult) {
        let duration_ms = result.duration.as_millis() as u64;

        if duration_ms >= self.error_threshold_ms {
            leptos::logging::error!(
                "[Timing] Slow mutation: {} took {}ms (threshold: {}ms)",
                ctx.mutation_name(),
                duration_ms,
                self.error_threshold_ms
            );
        } else if duration_ms >= self.warn_threshold_ms {
            leptos::logging::warn!(
                "[Timing] Mutation {} took {}ms",
                ctx.mutation_name(),
                duration_ms
            );
        }
    }

    fn after_action(&self, ctx: &ActionContext<S>, result: &ActionResult) {
        let duration_ms = result.duration.as_millis() as u64;

        if duration_ms >= self.error_threshold_ms {
            leptos::logging::error!(
                "[Timing] Slow action: {} took {}ms (threshold: {}ms)",
                ctx.action_name(),
                duration_ms,
                self.error_threshold_ms
            );
        } else if duration_ms >= self.warn_threshold_ms {
            leptos::logging::warn!(
                "[Timing] Action {} took {}ms",
                ctx.action_name(),
                duration_ms
            );
        }
    }

    fn name(&self) -> &'static str {
        "TimingMiddleware"
    }

    fn priority(&self) -> i32 {
        -50 // Run after most middleware but before logging
    }
}

// ============================================================================
// Built-in Middleware: Validation
// ============================================================================

/// Validation function type for state validation.
pub type ValidationFn<State> = Box<dyn Fn(&State) -> Result<(), String> + Send + Sync>;

/// Validation middleware that runs validators before mutations.
///
/// # Example
///
/// ```rust
/// use leptos_store::middleware::ValidationMiddleware;
/// # #[derive(Clone, Debug, Default)]
/// # struct MyState { count: i32 }
///
/// let validator = ValidationMiddleware::new()
///     .add_validator(|state: &MyState| {
///         if state.count < 0 {
///             Err("Count cannot be negative".to_string())
///         } else {
///             Ok(())
///         }
///     });
/// ```
pub struct ValidationMiddleware<State> {
    validators: Vec<ValidationFn<State>>,
}

impl<State> Default for ValidationMiddleware<State> {
    fn default() -> Self {
        Self::new()
    }
}

impl<State> ValidationMiddleware<State> {
    /// Create a new validation middleware.
    pub fn new() -> Self {
        Self {
            validators: Vec::new(),
        }
    }

    /// Add a validator function.
    pub fn add_validator<F>(mut self, validator: F) -> Self
    where
        F: Fn(&State) -> Result<(), String> + Send + Sync + 'static,
    {
        self.validators.push(Box::new(validator));
        self
    }
}

impl<S: Store> Middleware<S> for ValidationMiddleware<S::State> {
    fn before_mutate(&self, ctx: &MiddlewareContext<S>) -> MiddlewareResult {
        let state = ctx.state();

        for validator in &self.validators {
            if let Err(err) = validator(&state) {
                return MiddlewareResult::Abort(MiddlewareError::ValidationFailed(err));
            }
        }

        MiddlewareResult::Continue
    }

    fn name(&self) -> &'static str {
        "ValidationMiddleware"
    }

    fn priority(&self) -> i32 {
        100 // Run early to catch invalid states
    }
}

// ============================================================================
// Built-in Middleware: Tracing (feature-gated)
// ============================================================================

/// Tracing middleware for OpenTelemetry integration.
///
/// This middleware creates spans for mutations and actions, enabling
/// distributed tracing across your application.
///
/// # Feature
///
/// This middleware requires the `tracing` feature to be enabled.
#[cfg(feature = "tracing")]
pub struct TracingMiddleware {
    /// Service name for spans.
    service_name: &'static str,
}

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

#[cfg(feature = "tracing")]
impl TracingMiddleware {
    /// Create a new tracing middleware.
    pub fn new() -> Self {
        Self {
            service_name: "leptos-store",
        }
    }

    /// Set the service name for spans.
    pub fn with_service_name(mut self, name: &'static str) -> Self {
        self.service_name = name;
        self
    }
}

#[cfg(feature = "tracing")]
impl<S: Store> Middleware<S> for TracingMiddleware {
    fn before_mutate(&self, ctx: &MiddlewareContext<S>) -> MiddlewareResult {
        tracing::info_span!(
            "store.mutation",
            store = ctx.store_name(),
            mutation = ctx.mutation_name(),
            service = self.service_name,
        );
        MiddlewareResult::Continue
    }

    fn before_action(&self, ctx: &ActionContext<S>) -> MiddlewareResult {
        tracing::info_span!(
            "store.action",
            store = ctx.store_name(),
            action = ctx.action_name(),
            service = self.service_name,
        );
        MiddlewareResult::Continue
    }

    fn name(&self) -> &'static str {
        "TracingMiddleware"
    }

    fn priority(&self) -> i32 {
        200 // Run very early to capture the full span
    }
}

// ============================================================================
// 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)
    }
}

/// Create a middleware context for testing.
#[cfg(test)]
pub fn test_middleware_context<S: Store>(store: &S) -> MiddlewareContext<'_, S> {
    MiddlewareContext::new(store, "test_mutation")
}

/// Create an action context for testing.
#[cfg(test)]
pub fn test_action_context<S: Store>(store: &S) -> ActionContext<'_, S> {
    ActionContext::new(store, TypeId::of::<()>(), "test_action")
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use leptos::prelude::*;
    use std::sync::atomic::{AtomicU32, Ordering};

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

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

    impl TestStore {
        fn new() -> Self {
            Self {
                state: RwSignal::new(TestState::default()),
            }
        }
    }

    impl Store for TestStore {
        type State = TestState;

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

    // Test middleware that counts calls
    struct CountingMiddleware {
        before_mutate_count: AtomicU32,
        after_mutate_count: AtomicU32,
    }

    impl CountingMiddleware {
        fn new() -> Self {
            Self {
                before_mutate_count: AtomicU32::new(0),
                after_mutate_count: AtomicU32::new(0),
            }
        }

        fn before_count(&self) -> u32 {
            self.before_mutate_count.load(Ordering::SeqCst)
        }

        fn after_count(&self) -> u32 {
            self.after_mutate_count.load(Ordering::SeqCst)
        }
    }

    impl<S: Store> Middleware<S> for CountingMiddleware {
        fn before_mutate(&self, _ctx: &MiddlewareContext<S>) -> MiddlewareResult {
            self.before_mutate_count.fetch_add(1, Ordering::SeqCst);
            MiddlewareResult::Continue
        }

        fn after_mutate(&self, _ctx: &MiddlewareContext<S>, _result: &MutationResult) {
            self.after_mutate_count.fetch_add(1, Ordering::SeqCst);
        }
    }

    // Test middleware that aborts
    struct AbortingMiddleware;

    impl<S: Store> Middleware<S> for AbortingMiddleware {
        fn before_mutate(&self, _ctx: &MiddlewareContext<S>) -> MiddlewareResult {
            MiddlewareResult::Abort(MiddlewareError::Rejected("Test abort".to_string()))
        }
    }

    #[test]
    fn test_middleware_result_methods() {
        assert!(MiddlewareResult::Continue.should_continue());
        assert!(MiddlewareResult::Transform.should_continue());
        assert!(!MiddlewareResult::Skip.should_continue());
        assert!(
            !MiddlewareResult::Abort(MiddlewareError::Rejected("".to_string())).should_continue()
        );

        assert!(!MiddlewareResult::Continue.is_abort());
        assert!(MiddlewareResult::Abort(MiddlewareError::Rejected("".to_string())).is_abort());

        let abort = MiddlewareResult::Abort(MiddlewareError::Rejected("test".to_string()));
        assert!(abort.error().is_some());
        assert!(MiddlewareResult::Continue.error().is_none());
    }

    #[test]
    fn test_mutation_result() {
        let success = MutationResult::success(Duration::from_millis(10));
        assert!(success.success);
        assert!(success.error.is_none());

        let failure = MutationResult::failure(Duration::from_millis(5), "test error");
        assert!(!failure.success);
        assert_eq!(failure.error, Some("test error".to_string()));
    }

    #[test]
    fn test_action_result() {
        let success = ActionResult::success(Duration::from_millis(10));
        assert!(success.success);
        assert!(success.error.is_none());

        let success_with_output =
            ActionResult::success_with_output(Duration::from_millis(10), "String");
        assert!(success_with_output.success);
        assert_eq!(success_with_output.output_type, Some("String"));

        let failure = ActionResult::failure(Duration::from_millis(5), "action error");
        assert!(!failure.success);
        assert_eq!(failure.error, Some("action error".to_string()));
    }

    #[test]
    fn test_context_metadata() {
        let meta = ContextMetadata::new()
            .with_tag("test")
            .with_correlation_id("abc-123")
            .with_custom("key", "value");

        assert_eq!(meta.tags, vec!["test"]);
        assert_eq!(meta.correlation_id, Some("abc-123".to_string()));
        assert_eq!(meta.custom.get("key"), Some(&"value".to_string()));
    }

    #[test]
    fn test_middleware_chain_add_and_len() {
        let mut chain: MiddlewareChain<TestStore> = MiddlewareChain::new();
        assert!(chain.is_empty());
        assert_eq!(chain.len(), 0);

        chain.add(CountingMiddleware::new());
        assert!(!chain.is_empty());
        assert_eq!(chain.len(), 1);
    }

    #[test]
    fn test_middleware_chain_execution() {
        let store = TestStore::new();
        let counting = Arc::new(CountingMiddleware::new());

        let mut chain: MiddlewareChain<TestStore> = MiddlewareChain::new();
        chain.add_arc(counting.clone());

        let ctx = MiddlewareContext::new(&store, "test");

        let result = chain.before_mutate(&ctx);
        assert!(result.should_continue());
        assert_eq!(counting.before_count(), 1);

        chain.after_mutate(&ctx, &MutationResult::success(Duration::from_millis(1)));
        assert_eq!(counting.after_count(), 1);
    }

    #[test]
    fn test_middleware_chain_abort() {
        let store = TestStore::new();

        let mut chain: MiddlewareChain<TestStore> = MiddlewareChain::new();
        chain.add(AbortingMiddleware);

        let ctx = MiddlewareContext::new(&store, "test");
        let result = chain.before_mutate(&ctx);

        assert!(result.is_abort());
    }

    #[test]
    fn test_event_bus() {
        struct TestSubscriber {
            count: AtomicU32,
        }

        impl EventSubscriber for TestSubscriber {
            fn on_event(&self, _event: &StoreEvent) {
                self.count.fetch_add(1, Ordering::SeqCst);
            }
        }

        let bus = EventBus::new();
        assert_eq!(bus.subscriber_count(), 0);

        let subscriber = Arc::new(TestSubscriber {
            count: AtomicU32::new(0),
        });

        bus.subscribe_arc(subscriber.clone());
        assert_eq!(bus.subscriber_count(), 1);

        bus.emit(StoreEvent::StateChanged {
            store_id: StoreId::new::<TestStore>(),
            store_name: "TestStore",
            timestamp: 12345,
        });

        assert_eq!(subscriber.count.load(Ordering::SeqCst), 1);

        bus.clear();
        assert_eq!(bus.subscriber_count(), 0);
    }

    #[test]
    fn test_event_subscriber_filter() {
        struct FilteredSubscriber {
            mutation_count: AtomicU32,
        }

        impl EventSubscriber for FilteredSubscriber {
            fn on_event(&self, _event: &StoreEvent) {
                self.mutation_count.fetch_add(1, Ordering::SeqCst);
            }

            fn filter(&self, event: &StoreEvent) -> bool {
                matches!(event, StoreEvent::MutationCompleted { .. })
            }
        }

        let bus = EventBus::new();
        let subscriber = Arc::new(FilteredSubscriber {
            mutation_count: AtomicU32::new(0),
        });

        bus.subscribe_arc(subscriber.clone());

        // This should be filtered out
        bus.emit(StoreEvent::StateChanged {
            store_id: StoreId::new::<TestStore>(),
            store_name: "TestStore",
            timestamp: 12345,
        });
        assert_eq!(subscriber.mutation_count.load(Ordering::SeqCst), 0);

        // This should pass the filter
        bus.emit(StoreEvent::MutationCompleted {
            store_id: StoreId::new::<TestStore>(),
            name: "test",
            duration_ms: 10,
            success: true,
        });
        assert_eq!(subscriber.mutation_count.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn test_middleware_store() {
        let store = TestStore::new();
        let mw_store = MiddlewareStore::new(store);

        // Should implement Store trait
        let _state = mw_store.state();
        let _id = mw_store.id();
        let _name = mw_store.name();
    }

    #[test]
    fn test_middleware_error_display() {
        assert_eq!(
            MiddlewareError::Rejected("test".to_string()).to_string(),
            "Middleware rejected: test"
        );
        assert_eq!(
            MiddlewareError::ValidationFailed("invalid".to_string()).to_string(),
            "Validation failed: invalid"
        );
        assert_eq!(
            MiddlewareError::Timeout(1000).to_string(),
            "Middleware timed out after 1000ms"
        );
        assert_eq!(
            MiddlewareError::Internal("oops".to_string()).to_string(),
            "Middleware error: oops"
        );
    }
}