aranet-store 0.1.13

Local data persistence for Aranet sensor readings
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
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
//! Main store implementation.
//!
//! # SQLite Concurrency Model
//!
//! This store uses SQLite with WAL (Write-Ahead Logging) mode enabled for improved
//! concurrent read performance. Key concurrency characteristics:
//!
//! - **Multiple readers**: WAL mode allows multiple simultaneous read transactions
//! - **Single writer**: Only one write transaction can be active at a time
//! - **Non-blocking reads**: Read operations don't block write operations and vice versa
//!
//! ## Thread Safety
//!
//! The `Store` struct is **not thread-safe** by itself. When using `Store` in a
//! multi-threaded context (e.g., `aranet-service`), wrap it in a `Mutex` or similar:
//!
//! ```ignore
//! use tokio::sync::Mutex;
//! let store = Mutex::new(Store::open_default()?);
//!
//! // Access the store
//! let guard = store.lock().await;
//! let devices = guard.list_devices()?;
//! ```
//!
//! ## Performance Considerations
//!
//! - For high-concurrency scenarios, consider keeping lock hold times short
//! - Batch operations (like `insert_history`) are more efficient than individual inserts
//! - Query operations with indexes (`device_id`, `timestamp`) are optimized
//!
//! ## Database Location
//!
//! The default database path is platform-specific:
//! - **Linux**: `~/.local/share/aranet/data.db`
//! - **macOS**: `~/Library/Application Support/aranet/data.db`
//! - **Windows**: `C:\Users\<user>\AppData\Local\aranet\data.db`

use std::path::Path;

use rusqlite::{Connection, OptionalExtension};
use time::OffsetDateTime;
use tracing::{debug, info, warn};

use aranet_types::{CurrentReading, DeviceInfo, DeviceType, HistoryRecord, Status};

/// Safely convert a Unix timestamp to OffsetDateTime.
///
/// Returns UNIX_EPOCH if the timestamp is invalid (corrupted database data).
/// Callers should be aware that UNIX_EPOCH indicates a corrupted value.
fn timestamp_from_unix(ts: i64) -> OffsetDateTime {
    OffsetDateTime::from_unix_timestamp(ts).unwrap_or_else(|_| {
        warn!(
            "Corrupted timestamp {} in database, substituting UNIX_EPOCH. \
             Consider running a database integrity check.",
            ts
        );
        OffsetDateTime::UNIX_EPOCH
    })
}

use crate::error::{Error, Result};
use crate::models::{StoredDevice, StoredHistoryRecord, StoredReading, SyncState};
use crate::queries::{HistoryQuery, ReadingQuery};
use crate::schema;

/// SQLite-based store for Aranet sensor data.
///
/// `Store` provides persistent storage for sensor readings, history records,
/// and device metadata using SQLite. It supports:
///
/// - **Device management**: Track multiple Aranet devices with metadata
/// - **Current readings**: Store real-time sensor data with timestamps
/// - **History records**: Cache device history to avoid re-downloading
/// - **Incremental sync**: Track sync state for efficient history updates
/// - **Export/Import**: CSV and JSON formats for data portability
///
/// # Thread Safety
///
/// `Store` is **not thread-safe**. For concurrent access (e.g., in `aranet-service`),
/// wrap it in a `Mutex`:
///
/// ```ignore
/// use std::sync::Arc;
/// use tokio::sync::Mutex;
/// use aranet_store::Store;
///
/// let store = Arc::new(Mutex::new(Store::open_default()?));
///
/// // In async context:
/// let guard = store.lock().await;
/// let devices = guard.list_devices()?;
/// ```
///
/// # Example
///
/// ```no_run
/// use aranet_store::{Store, ReadingQuery, HistoryQuery};
/// use aranet_types::CurrentReading;
///
/// // Open the default database
/// let store = Store::open_default()?;
///
/// // Store a reading
/// let reading = CurrentReading::default();
/// store.insert_reading("Aranet4 17C3C", &reading)?;
///
/// // Query readings
/// let query = ReadingQuery::new().device("Aranet4 17C3C").limit(10);
/// let readings = store.query_readings(&query)?;
///
/// // Export history to CSV
/// let csv = store.export_history_csv(&HistoryQuery::new())?;
/// # Ok::<(), aranet_store::Error>(())
/// ```
pub struct Store {
    conn: Connection,
}

impl Store {
    /// Open or create a database at the given path.
    ///
    /// Creates parent directories if they don't exist. The database is
    /// initialized with WAL mode for better concurrent read performance.
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the SQLite database file
    ///
    /// # Example
    ///
    /// ```no_run
    /// use aranet_store::Store;
    ///
    /// let store = Store::open("/path/to/my/aranet.db")?;
    /// # Ok::<(), aranet_store::Error>(())
    /// ```
    pub fn open<P: AsRef<Path>>(path: P) -> Result<Self> {
        let path = path.as_ref();

        // Create parent directories if needed
        if let Some(parent) = path.parent()
            && !parent.exists()
        {
            std::fs::create_dir_all(parent).map_err(|e| Error::CreateDirectory {
                path: parent.to_path_buf(),
                source: e,
            })?;
        }

        info!("Opening database at {}", path.display());
        let conn = Connection::open(path)?;

        // Enable foreign keys and WAL mode for better performance
        conn.execute_batch(
            "PRAGMA foreign_keys = ON;
             PRAGMA journal_mode = WAL;
             PRAGMA synchronous = NORMAL;",
        )?;

        // Initialize schema
        schema::initialize(&conn)?;

        Ok(Self { conn })
    }

    /// Open the database at the platform-specific default location.
    ///
    /// Default paths by platform:
    /// - **Linux**: `~/.local/share/aranet/data.db`
    /// - **macOS**: `~/Library/Application Support/aranet/data.db`
    /// - **Windows**: `C:\Users\<user>\AppData\Local\aranet\data.db`
    ///
    /// # Example
    ///
    /// ```no_run
    /// use aranet_store::Store;
    ///
    /// let store = Store::open_default()?;
    /// # Ok::<(), aranet_store::Error>(())
    /// ```
    pub fn open_default() -> Result<Self> {
        Self::open(crate::default_db_path())
    }

    /// Open an in-memory database.
    ///
    /// Useful for testing or temporary storage. Data is lost when the
    /// `Store` is dropped.
    ///
    /// # Example
    ///
    /// ```
    /// use aranet_store::Store;
    ///
    /// let store = Store::open_in_memory()?;
    /// // Use for testing...
    /// # Ok::<(), aranet_store::Error>(())
    /// ```
    pub fn open_in_memory() -> Result<Self> {
        let conn = Connection::open_in_memory()?;
        conn.execute_batch("PRAGMA foreign_keys = ON;")?;
        schema::initialize(&conn)?;
        Ok(Self { conn })
    }

    // === Device operations ===

    /// Get or create a device entry, updating timestamps.
    ///
    /// If the device exists, updates its `last_seen` timestamp and optionally
    /// the name. If it doesn't exist, creates a new entry with the current time
    /// as both `first_seen` and `last_seen`.
    ///
    /// # Arguments
    ///
    /// * `device_id` - Unique identifier for the device (typically BLE address)
    /// * `name` - Optional human-readable name for the device
    ///
    /// # Returns
    ///
    /// The device record after insert/update.
    ///
    /// # Example
    ///
    /// ```
    /// use aranet_store::Store;
    ///
    /// let store = Store::open_in_memory()?;
    /// let device = store.upsert_device("Aranet4 17C3C", Some("Kitchen"))?;
    /// assert_eq!(device.name, Some("Kitchen".to_string()));
    /// # Ok::<(), aranet_store::Error>(())
    /// ```
    pub fn upsert_device(&self, device_id: &str, name: Option<&str>) -> Result<StoredDevice> {
        let now = OffsetDateTime::now_utc().unix_timestamp();

        self.conn.execute(
            "INSERT INTO devices (id, name, first_seen, last_seen) VALUES (?1, ?2, ?3, ?3)
             ON CONFLICT(id) DO UPDATE SET 
                name = COALESCE(?2, name),
                last_seen = ?3",
            rusqlite::params![device_id, name, now],
        )?;

        self.get_device(device_id)?
            .ok_or_else(|| Error::DeviceNotFound(device_id.to_string()))
    }

    /// Update device metadata (name and type).
    ///
    /// This is a simpler version of `update_device_info` for when you only have
    /// basic device information (e.g., from BLE advertisement or connection).
    pub fn update_device_metadata(
        &self,
        device_id: &str,
        name: Option<&str>,
        device_type: Option<DeviceType>,
    ) -> Result<()> {
        let device_type_str = device_type.map(|dt| format!("{:?}", dt));
        let now = OffsetDateTime::now_utc().unix_timestamp();

        self.conn.execute(
            "UPDATE devices SET
                name = COALESCE(?2, name),
                device_type = COALESCE(?3, device_type),
                last_seen = ?4
             WHERE id = ?1",
            rusqlite::params![device_id, name, device_type_str, now],
        )?;

        Ok(())
    }

    /// Update device info from DeviceInfo.
    ///
    /// Device type is automatically inferred from the model name using
    /// `DeviceType::from_name()`, which handles all known Aranet device naming patterns.
    pub fn update_device_info(&self, device_id: &str, info: &DeviceInfo) -> Result<()> {
        // Use the shared DeviceType::from_name() for consistent device type detection
        let device_type = DeviceType::from_name(&info.model).map(|dt| format!("{:?}", dt));

        let name = if info.name.is_empty() {
            None
        } else {
            Some(&info.name)
        };

        self.conn.execute(
            "UPDATE devices SET
                name = COALESCE(?2, name),
                device_type = COALESCE(?3, device_type),
                serial = COALESCE(?4, serial),
                firmware = COALESCE(?5, firmware),
                hardware = COALESCE(?6, hardware),
                last_seen = ?7
             WHERE id = ?1",
            rusqlite::params![
                device_id,
                name,
                device_type,
                &info.serial,
                &info.firmware,
                &info.hardware,
                OffsetDateTime::now_utc().unix_timestamp()
            ],
        )?;

        Ok(())
    }

    /// Get a device by its unique identifier.
    ///
    /// # Arguments
    ///
    /// * `device_id` - The device identifier to look up
    ///
    /// # Returns
    ///
    /// `Some(StoredDevice)` if found, `None` if the device doesn't exist.
    ///
    /// # Example
    ///
    /// ```
    /// use aranet_store::Store;
    ///
    /// let store = Store::open_in_memory()?;
    /// store.upsert_device("Aranet4 17C3C", Some("Kitchen"))?;
    ///
    /// if let Some(device) = store.get_device("Aranet4 17C3C")? {
    ///     println!("Found device: {:?}", device.name);
    /// }
    /// # Ok::<(), aranet_store::Error>(())
    /// ```
    pub fn get_device(&self, device_id: &str) -> Result<Option<StoredDevice>> {
        let mut stmt = self.conn.prepare(
            "SELECT id, name, device_type, serial, firmware, hardware, first_seen, last_seen 
             FROM devices WHERE id = ?",
        )?;

        let device = stmt
            .query_row([device_id], |row| {
                Ok(StoredDevice {
                    id: row.get(0)?,
                    name: row.get(1)?,
                    device_type: row
                        .get::<_, Option<String>>(2)?
                        .and_then(|s| parse_device_type(&s)),
                    serial: row.get(3)?,
                    firmware: row.get(4)?,
                    hardware: row.get(5)?,
                    first_seen: timestamp_from_unix(row.get(6)?),
                    last_seen: timestamp_from_unix(row.get(7)?),
                })
            })
            .optional()?;

        Ok(device)
    }

    /// List all known devices, ordered by most recently seen first.
    ///
    /// # Returns
    ///
    /// A vector of all stored devices, sorted by `last_seen` descending.
    ///
    /// # Example
    ///
    /// ```
    /// use aranet_store::Store;
    ///
    /// let store = Store::open_in_memory()?;
    /// store.upsert_device("device-1", Some("Kitchen"))?;
    /// store.upsert_device("device-2", Some("Bedroom"))?;
    ///
    /// let devices = store.list_devices()?;
    /// for device in devices {
    ///     println!("{}: {:?}", device.id, device.name);
    /// }
    /// # Ok::<(), aranet_store::Error>(())
    /// ```
    pub fn list_devices(&self) -> Result<Vec<StoredDevice>> {
        let mut stmt = self.conn.prepare(
            "SELECT id, name, device_type, serial, firmware, hardware, first_seen, last_seen 
             FROM devices ORDER BY last_seen DESC",
        )?;

        let devices = stmt
            .query_map([], |row| {
                Ok(StoredDevice {
                    id: row.get(0)?,
                    name: row.get(1)?,
                    device_type: row
                        .get::<_, Option<String>>(2)?
                        .and_then(|s| parse_device_type(&s)),
                    serial: row.get(3)?,
                    firmware: row.get(4)?,
                    hardware: row.get(5)?,
                    first_seen: timestamp_from_unix(row.get(6)?),
                    last_seen: timestamp_from_unix(row.get(7)?),
                })
            })?
            .collect::<std::result::Result<Vec<_>, _>>()?;

        Ok(devices)
    }

    /// Delete a device and all associated data (readings, history, sync state).
    ///
    /// All deletions are performed within a transaction to ensure atomicity.
    /// Returns true if the device was deleted, false if it didn't exist.
    pub fn delete_device(&self, device_id: &str) -> Result<bool> {
        let tx = self.conn.unchecked_transaction()?;

        // Delete in order: history, readings, sync_state, device
        tx.execute(
            "DELETE FROM history WHERE device_id = ?1",
            rusqlite::params![device_id],
        )?;

        tx.execute(
            "DELETE FROM readings WHERE device_id = ?1",
            rusqlite::params![device_id],
        )?;

        tx.execute(
            "DELETE FROM sync_state WHERE device_id = ?1",
            rusqlite::params![device_id],
        )?;

        let rows_deleted = tx.execute(
            "DELETE FROM devices WHERE id = ?1",
            rusqlite::params![device_id],
        )?;

        tx.commit()?;

        Ok(rows_deleted > 0)
    }
}

fn parse_device_type(s: &str) -> Option<DeviceType> {
    match s {
        "Aranet4" => Some(DeviceType::Aranet4),
        "Aranet2" => Some(DeviceType::Aranet2),
        "AranetRadon" => Some(DeviceType::AranetRadon),
        "AranetRadiation" => Some(DeviceType::AranetRadiation),
        _ => None,
    }
}

fn parse_status(s: &str) -> Status {
    match s {
        "Green" => Status::Green,
        "Yellow" => Status::Yellow,
        "Red" => Status::Red,
        "Error" => Status::Error,
        _ => Status::Green,
    }
}

// Reading operations
impl Store {
    /// Insert a current reading from a device.
    ///
    /// Automatically creates the device entry if it doesn't exist. The reading
    /// is stored with its `captured_at` timestamp, or the current time if not set.
    ///
    /// # Arguments
    ///
    /// * `device_id` - The device that produced this reading
    /// * `reading` - The sensor reading to store
    ///
    /// # Returns
    ///
    /// The database row ID of the inserted reading.
    ///
    /// # Example
    ///
    /// ```
    /// use aranet_store::Store;
    /// use aranet_types::{CurrentReading, Status};
    ///
    /// let store = Store::open_in_memory()?;
    /// let reading = CurrentReading {
    ///     co2: 800,
    ///     temperature: 22.5,
    ///     pressure: 1013.0,
    ///     humidity: 45,
    ///     battery: 85,
    ///     status: Status::Green,
    ///     ..Default::default()
    /// };
    ///
    /// let row_id = store.insert_reading("Aranet4 17C3C", &reading)?;
    /// # Ok::<(), aranet_store::Error>(())
    /// ```
    pub fn insert_reading(&self, device_id: &str, reading: &CurrentReading) -> Result<i64> {
        // Ensure device exists
        self.upsert_device(device_id, None)?;

        let captured_at = reading
            .captured_at
            .unwrap_or_else(OffsetDateTime::now_utc)
            .unix_timestamp();

        self.conn.execute(
            "INSERT INTO readings (device_id, captured_at, co2, temperature, pressure,
             humidity, battery, status, radon, radiation_rate, radiation_total)
             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)",
            rusqlite::params![
                device_id,
                captured_at,
                reading.co2,
                reading.temperature,
                reading.pressure,
                reading.humidity,
                reading.battery,
                format!("{:?}", reading.status),
                reading.radon,
                reading.radiation_rate,
                reading.radiation_total,
            ],
        )?;

        Ok(self.conn.last_insert_rowid())
    }

    /// Query readings with optional filters.
    ///
    /// Use [`ReadingQuery`] to build queries with device, time range,
    /// pagination, and ordering filters.
    ///
    /// # Arguments
    ///
    /// * `query` - Query parameters built using [`ReadingQuery`]
    ///
    /// # Example
    ///
    /// ```
    /// use aranet_store::{Store, ReadingQuery};
    /// use time::{OffsetDateTime, Duration};
    ///
    /// let store = Store::open_in_memory()?;
    ///
    /// // Query last 24 hours for a specific device
    /// let yesterday = OffsetDateTime::now_utc() - Duration::hours(24);
    /// let query = ReadingQuery::new()
    ///     .device("Aranet4 17C3C")
    ///     .since(yesterday)
    ///     .limit(100);
    ///
    /// let readings = store.query_readings(&query)?;
    /// for reading in readings {
    ///     println!("CO2: {} ppm at {}", reading.co2, reading.captured_at);
    /// }
    /// # Ok::<(), aranet_store::Error>(())
    /// ```
    pub fn query_readings(&self, query: &ReadingQuery) -> Result<Vec<StoredReading>> {
        let sql = query.build_sql();
        let (_, params) = query.build_where();

        debug!("Executing query: {}", sql);

        let params_ref: Vec<&dyn rusqlite::ToSql> = params.iter().map(|p| p.as_ref()).collect();

        let mut stmt = self.conn.prepare(&sql)?;
        let readings = stmt
            .query_map(params_ref.as_slice(), |row| {
                Ok(StoredReading {
                    id: row.get(0)?,
                    device_id: row.get(1)?,
                    captured_at: timestamp_from_unix(row.get(2)?),
                    co2: row.get::<_, i64>(3)? as u16,
                    temperature: row.get(4)?,
                    pressure: row.get(5)?,
                    humidity: row.get::<_, i64>(6)? as u8,
                    battery: row.get::<_, i64>(7)? as u8,
                    status: parse_status(&row.get::<_, String>(8)?),
                    radon: row.get::<_, Option<i64>>(9)?.map(|v| v as u32),
                    radiation_rate: row.get(10)?,
                    radiation_total: row.get(11)?,
                })
            })?
            .collect::<std::result::Result<Vec<_>, _>>()?;

        Ok(readings)
    }

    /// Get the most recent reading for a device.
    ///
    /// Convenience method equivalent to `query_readings` with `limit(1)`.
    ///
    /// # Arguments
    ///
    /// * `device_id` - The device to get the latest reading for
    ///
    /// # Returns
    ///
    /// The most recent reading, or `None` if no readings exist for this device.
    ///
    /// # Example
    ///
    /// ```
    /// use aranet_store::Store;
    ///
    /// let store = Store::open_in_memory()?;
    ///
    /// if let Some(reading) = store.get_latest_reading("Aranet4 17C3C")? {
    ///     println!("Latest CO2: {} ppm", reading.co2);
    /// }
    /// # Ok::<(), aranet_store::Error>(())
    /// ```
    pub fn get_latest_reading(&self, device_id: &str) -> Result<Option<StoredReading>> {
        let query = ReadingQuery::new().device(device_id).limit(1);
        let mut readings = self.query_readings(&query)?;
        Ok(readings.pop())
    }

    /// Count total readings, optionally filtered by device.
    ///
    /// # Arguments
    ///
    /// * `device_id` - If `Some`, count only readings for this device.
    ///   If `None`, count all readings across all devices.
    ///
    /// # Example
    ///
    /// ```
    /// use aranet_store::Store;
    ///
    /// let store = Store::open_in_memory()?;
    ///
    /// // Count all readings
    /// let total = store.count_readings(None)?;
    ///
    /// // Count for specific device
    /// let device_count = store.count_readings(Some("Aranet4 17C3C"))?;
    /// # Ok::<(), aranet_store::Error>(())
    /// ```
    pub fn count_readings(&self, device_id: Option<&str>) -> Result<u64> {
        let count: i64 = match device_id {
            Some(id) => self.conn.query_row(
                "SELECT COUNT(*) FROM readings WHERE device_id = ?",
                [id],
                |row| row.get(0),
            )?,
            None => self
                .conn
                .query_row("SELECT COUNT(*) FROM readings", [], |row| row.get(0))?,
        };

        Ok(count as u64)
    }
}

// History operations
impl Store {
    /// Insert history records with automatic deduplication.
    ///
    /// Records are deduplicated by `(device_id, timestamp)` - if a record with
    /// the same timestamp already exists for this device, it is skipped.
    /// This allows safe re-syncing without creating duplicates.
    ///
    /// # Arguments
    ///
    /// * `device_id` - The device these history records belong to
    /// * `records` - Slice of history records to insert
    ///
    /// # Returns
    ///
    /// The number of records actually inserted (excluding duplicates).
    ///
    /// # Example
    ///
    /// ```
    /// use aranet_store::Store;
    /// use aranet_types::HistoryRecord;
    /// use time::OffsetDateTime;
    ///
    /// let store = Store::open_in_memory()?;
    ///
    /// let records = vec![
    ///     HistoryRecord {
    ///         timestamp: OffsetDateTime::now_utc(),
    ///         co2: 800,
    ///         temperature: 22.5,
    ///         pressure: 1013.0,
    ///         humidity: 45,
    ///         radon: None,
    ///         radiation_rate: None,
    ///         radiation_total: None,
    ///     },
    /// ];
    ///
    /// let inserted = store.insert_history("Aranet4 17C3C", &records)?;
    /// println!("Inserted {} new records", inserted);
    /// # Ok::<(), aranet_store::Error>(())
    /// ```
    pub fn insert_history(&self, device_id: &str, records: &[HistoryRecord]) -> Result<usize> {
        // Ensure device exists
        self.upsert_device(device_id, None)?;

        let synced_at = OffsetDateTime::now_utc().unix_timestamp();
        let mut inserted = 0;

        for record in records {
            let result = self.conn.execute(
                "INSERT OR IGNORE INTO history (device_id, timestamp, synced_at, co2,
                 temperature, pressure, humidity, radon, radiation_rate, radiation_total)
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)",
                rusqlite::params![
                    device_id,
                    record.timestamp.unix_timestamp(),
                    synced_at,
                    record.co2,
                    record.temperature,
                    record.pressure,
                    record.humidity,
                    record.radon,
                    record.radiation_rate,
                    record.radiation_total,
                ],
            )?;
            inserted += result;
        }

        info!(
            "Inserted {} new history records for {}",
            inserted, device_id
        );
        Ok(inserted)
    }

    /// Query history records with optional filters.
    ///
    /// Use [`HistoryQuery`] to build queries with device, time range,
    /// pagination, and ordering filters.
    ///
    /// # Arguments
    ///
    /// * `query` - Query parameters built using [`HistoryQuery`]
    ///
    /// # Example
    ///
    /// ```
    /// use aranet_store::{Store, HistoryQuery};
    /// use time::{OffsetDateTime, Duration};
    ///
    /// let store = Store::open_in_memory()?;
    ///
    /// // Query last week's history for a device
    /// let week_ago = OffsetDateTime::now_utc() - Duration::days(7);
    /// let query = HistoryQuery::new()
    ///     .device("Aranet4 17C3C")
    ///     .since(week_ago)
    ///     .oldest_first();
    ///
    /// let records = store.query_history(&query)?;
    /// # Ok::<(), aranet_store::Error>(())
    /// ```
    pub fn query_history(&self, query: &HistoryQuery) -> Result<Vec<StoredHistoryRecord>> {
        let mut conditions = Vec::new();
        let mut params: Vec<Box<dyn rusqlite::ToSql>> = Vec::new();

        if let Some(ref device_id) = query.device_id {
            conditions.push("device_id = ?");
            params.push(Box::new(device_id.clone()));
        }

        if let Some(since) = query.since {
            conditions.push("timestamp >= ?");
            params.push(Box::new(since.unix_timestamp()));
        }

        if let Some(until) = query.until {
            conditions.push("timestamp <= ?");
            params.push(Box::new(until.unix_timestamp()));
        }

        let where_clause = if conditions.is_empty() {
            String::new()
        } else {
            format!("WHERE {}", conditions.join(" AND "))
        };

        let order = if query.newest_first { "DESC" } else { "ASC" };

        let mut sql = format!(
            "SELECT id, device_id, timestamp, synced_at, co2, temperature, pressure,
             humidity, radon, radiation_rate, radiation_total
             FROM history {} ORDER BY timestamp {}",
            where_clause, order
        );

        if let Some(limit) = query.limit {
            sql.push_str(&format!(" LIMIT {}", limit));
        }

        if let Some(offset) = query.offset {
            sql.push_str(&format!(" OFFSET {}", offset));
        }

        let params_ref: Vec<&dyn rusqlite::ToSql> = params.iter().map(|p| p.as_ref()).collect();

        let mut stmt = self.conn.prepare(&sql)?;
        let records = stmt
            .query_map(params_ref.as_slice(), |row| {
                Ok(StoredHistoryRecord {
                    id: row.get(0)?,
                    device_id: row.get(1)?,
                    timestamp: timestamp_from_unix(row.get(2)?),
                    synced_at: timestamp_from_unix(row.get(3)?),
                    co2: row.get::<_, i64>(4)? as u16,
                    temperature: row.get(5)?,
                    pressure: row.get(6)?,
                    humidity: row.get::<_, i64>(7)? as u8,
                    radon: row.get::<_, Option<i64>>(8)?.map(|v| v as u32),
                    radiation_rate: row.get(9)?,
                    radiation_total: row.get(10)?,
                })
            })?
            .collect::<std::result::Result<Vec<_>, _>>()?;

        Ok(records)
    }

    /// Count total history records, optionally filtered by device.
    ///
    /// # Arguments
    ///
    /// * `device_id` - If `Some`, count only records for this device.
    ///   If `None`, count all records across all devices.
    ///
    /// # Example
    ///
    /// ```
    /// use aranet_store::Store;
    ///
    /// let store = Store::open_in_memory()?;
    ///
    /// // Count all history records
    /// let total = store.count_history(None)?;
    ///
    /// // Count for specific device
    /// let device_count = store.count_history(Some("Aranet4 17C3C"))?;
    /// # Ok::<(), aranet_store::Error>(())
    /// ```
    pub fn count_history(&self, device_id: Option<&str>) -> Result<u64> {
        let count: i64 = match device_id {
            Some(id) => self.conn.query_row(
                "SELECT COUNT(*) FROM history WHERE device_id = ?",
                [id],
                |row| row.get(0),
            )?,
            None => self
                .conn
                .query_row("SELECT COUNT(*) FROM history", [], |row| row.get(0))?,
        };

        Ok(count as u64)
    }
}

// Sync state operations
impl Store {
    /// Get the sync state for a device.
    ///
    /// Sync state tracks the last downloaded history index and total readings,
    /// enabling incremental history downloads instead of re-downloading everything.
    ///
    /// # Arguments
    ///
    /// * `device_id` - The device to get sync state for
    ///
    /// # Returns
    ///
    /// The sync state if any history has been synced, `None` for new devices.
    ///
    /// # Example
    ///
    /// ```
    /// use aranet_store::Store;
    ///
    /// let store = Store::open_in_memory()?;
    /// store.upsert_device("Aranet4 17C3C", None)?;
    ///
    /// // Initially no sync state
    /// let state = store.get_sync_state("Aranet4 17C3C")?;
    /// assert!(state.is_none());
    /// # Ok::<(), aranet_store::Error>(())
    /// ```
    pub fn get_sync_state(&self, device_id: &str) -> Result<Option<SyncState>> {
        let mut stmt = self.conn.prepare(
            "SELECT device_id, last_history_index, total_readings, last_sync_at
             FROM sync_state WHERE device_id = ?",
        )?;

        let state = stmt
            .query_row([device_id], |row| {
                Ok(SyncState {
                    device_id: row.get(0)?,
                    last_history_index: row.get::<_, Option<i64>>(1)?.map(|v| v as u16),
                    total_readings: row.get::<_, Option<i64>>(2)?.map(|v| v as u16),
                    last_sync_at: row.get::<_, Option<i64>>(3)?.map(timestamp_from_unix),
                })
            })
            .optional()?;

        Ok(state)
    }

    /// Update sync state after a successful history download.
    ///
    /// Call this after downloading history records to track progress. The next
    /// sync can then use [`calculate_sync_start`](Self::calculate_sync_start) to
    /// determine which records to download.
    ///
    /// # Arguments
    ///
    /// * `device_id` - The device that was synced
    /// * `last_index` - The highest history index that was downloaded (1-based)
    /// * `total_readings` - Total readings on the device at sync time
    ///
    /// # Example
    ///
    /// ```
    /// use aranet_store::Store;
    ///
    /// let store = Store::open_in_memory()?;
    /// store.upsert_device("Aranet4 17C3C", None)?;
    ///
    /// // After downloading all 500 history records
    /// store.update_sync_state("Aranet4 17C3C", 500, 500)?;
    ///
    /// // Verify sync state was saved
    /// let state = store.get_sync_state("Aranet4 17C3C")?.unwrap();
    /// assert_eq!(state.last_history_index, Some(500));
    /// # Ok::<(), aranet_store::Error>(())
    /// ```
    pub fn update_sync_state(
        &self,
        device_id: &str,
        last_index: u16,
        total_readings: u16,
    ) -> Result<()> {
        let now = OffsetDateTime::now_utc().unix_timestamp();

        self.conn.execute(
            "INSERT INTO sync_state (device_id, last_history_index, total_readings, last_sync_at)
             VALUES (?1, ?2, ?3, ?4)
             ON CONFLICT(device_id) DO UPDATE SET
                last_history_index = ?2,
                total_readings = ?3,
                last_sync_at = ?4",
            rusqlite::params![device_id, last_index, total_readings, now],
        )?;

        debug!(
            "Updated sync state for {}: index={}, total={}",
            device_id, last_index, total_readings
        );

        Ok(())
    }

    /// Calculate the start index for incremental sync.
    ///
    /// Returns the index to start downloading from (1-based).
    /// If the device has new readings since last sync, returns the next index.
    /// If this is the first sync, returns 1 to download all.
    ///
    /// # Buffer Wrap-Around Detection
    ///
    /// Aranet devices have a circular buffer (e.g., ~2016 readings for Aranet4 at 10-min
    /// intervals). When the buffer fills up, new readings replace the oldest ones, but
    /// `total_readings` stays constant. This function detects this wrap-around case by
    /// comparing the latest stored timestamp with the expected time since last sync.
    pub fn calculate_sync_start(&self, device_id: &str, current_total: u16) -> Result<u16> {
        let state = self.get_sync_state(device_id)?;

        match state {
            Some(s) if s.total_readings == Some(current_total) => {
                // Same total readings as last sync - could mean:
                // 1. No new readings (buffer not full, recent sync)
                // 2. Buffer wrapped (old readings replaced with new)
                // 3. History cache was cleared but sync state exists

                // Check if buffer has likely wrapped by comparing timestamps
                if s.last_sync_at.is_some() {
                    let latest_stored = self.get_latest_history_timestamp(device_id)?;

                    match latest_stored {
                        Some(latest_ts) => {
                            let now = OffsetDateTime::now_utc();
                            let time_since_latest = now - latest_ts;

                            // If more than 10 minutes since latest record, new data likely exists
                            // (10 min is the longest standard Aranet4 interval)
                            if time_since_latest > time::Duration::minutes(10) {
                                debug!(
                                    "Buffer may have wrapped for {} (latest record is {} min old), doing full sync",
                                    device_id,
                                    time_since_latest.whole_minutes()
                                );
                                return Ok(1);
                            }

                            // Recent sync and no indication of wrap-around
                            debug!("No new readings for {}", device_id);
                            Ok(current_total + 1)
                        }
                        None => {
                            // Sync state exists but no history records - cache was likely cleared
                            // Do a full sync to repopulate
                            debug!(
                                "Sync state exists but no history for {}, doing full sync",
                                device_id
                            );
                            Ok(1)
                        }
                    }
                } else {
                    // No last_sync_at - shouldn't happen but do full sync to be safe
                    debug!("No sync timestamp for {}, doing full sync", device_id);
                    Ok(1)
                }
            }
            Some(s) if s.last_history_index.is_some() => {
                // We have previous state, calculate new records
                let last_index = s.last_history_index.unwrap();
                let prev_total = s.total_readings.unwrap_or(0);

                // Check if device was reset (current_total < prev_total)
                if current_total < prev_total {
                    debug!(
                        "Device total decreased ({} -> {}) for {}, device was reset - doing full sync",
                        prev_total, current_total, device_id
                    );
                    return Ok(1);
                }

                let new_count = current_total.saturating_sub(prev_total);

                if new_count > 0 {
                    // Start from where we left off
                    let start = last_index.saturating_add(1);

                    // Validate start index doesn't exceed current total
                    // This can happen if device buffer wrapped or was reset
                    if start > current_total {
                        debug!(
                            "Start index {} exceeds device total {} for {}, doing full sync",
                            start, current_total, device_id
                        );
                        return Ok(1);
                    }

                    debug!(
                        "Incremental sync for {}: {} new readings, starting at {}",
                        device_id, new_count, start
                    );
                    Ok(start)
                } else {
                    Ok(current_total + 1)
                }
            }
            _ => {
                // First sync - download all
                debug!(
                    "First sync for {}: downloading all {} readings",
                    device_id, current_total
                );
                Ok(1)
            }
        }
    }

    /// Get the timestamp of the most recent history record for a device.
    ///
    /// Returns `None` if no history exists for the device.
    fn get_latest_history_timestamp(&self, device_id: &str) -> Result<Option<OffsetDateTime>> {
        let ts: Option<i64> = self
            .conn
            .query_row(
                "SELECT MAX(timestamp) FROM history WHERE device_id = ?",
                [device_id],
                |row| row.get(0),
            )
            .optional()?
            .flatten();

        Ok(ts.map(timestamp_from_unix))
    }
}

/// Aggregate statistics for history data.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct HistoryStats {
    /// Number of records.
    pub count: u64,
    /// Minimum values.
    pub min: HistoryAggregates,
    /// Maximum values.
    pub max: HistoryAggregates,
    /// Average values.
    pub avg: HistoryAggregates,
    /// Time range of records.
    pub time_range: Option<(OffsetDateTime, OffsetDateTime)>,
}

/// Aggregate values for a single metric set.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct HistoryAggregates {
    /// CO2 in ppm.
    pub co2: Option<f64>,
    /// Temperature in Celsius.
    pub temperature: Option<f64>,
    /// Pressure in hPa.
    pub pressure: Option<f64>,
    /// Humidity percentage.
    pub humidity: Option<f64>,
    /// Radon in Bq/m3 (for radon devices).
    pub radon: Option<f64>,
}

// Aggregate and export operations
impl Store {
    /// Calculate aggregate statistics for history records.
    ///
    /// Computes min, max, and average values for all sensor metrics across
    /// the records matching the query. Useful for dashboards and reports.
    ///
    /// # Arguments
    ///
    /// * `query` - Filter which records to include in the statistics
    ///
    /// # Example
    ///
    /// ```
    /// use aranet_store::{Store, HistoryQuery};
    /// use time::{OffsetDateTime, Duration};
    ///
    /// let store = Store::open_in_memory()?;
    ///
    /// // Get stats for last 24 hours
    /// let yesterday = OffsetDateTime::now_utc() - Duration::hours(24);
    /// let query = HistoryQuery::new()
    ///     .device("Aranet4 17C3C")
    ///     .since(yesterday);
    ///
    /// let stats = store.history_stats(&query)?;
    /// if let Some(avg_co2) = stats.avg.co2 {
    ///     println!("Average CO2: {:.0} ppm", avg_co2);
    /// }
    /// if let Some((start, end)) = stats.time_range {
    ///     println!("Time range: {} to {}", start, end);
    /// }
    /// # Ok::<(), aranet_store::Error>(())
    /// ```
    pub fn history_stats(&self, query: &HistoryQuery) -> Result<HistoryStats> {
        let mut conditions = Vec::new();
        let mut params: Vec<Box<dyn rusqlite::ToSql>> = Vec::new();

        if let Some(ref device_id) = query.device_id {
            conditions.push("device_id = ?");
            params.push(Box::new(device_id.clone()));
        }

        if let Some(since) = query.since {
            conditions.push("timestamp >= ?");
            params.push(Box::new(since.unix_timestamp()));
        }

        if let Some(until) = query.until {
            conditions.push("timestamp <= ?");
            params.push(Box::new(until.unix_timestamp()));
        }

        let where_clause = if conditions.is_empty() {
            String::new()
        } else {
            format!("WHERE {}", conditions.join(" AND "))
        };

        let sql = format!(
            "SELECT
                COUNT(*) as count,
                MIN(co2) as min_co2, MAX(co2) as max_co2, AVG(co2) as avg_co2,
                MIN(temperature) as min_temp, MAX(temperature) as max_temp, AVG(temperature) as avg_temp,
                MIN(pressure) as min_press, MAX(pressure) as max_press, AVG(pressure) as avg_press,
                MIN(humidity) as min_hum, MAX(humidity) as max_hum, AVG(humidity) as avg_hum,
                MIN(radon) as min_radon, MAX(radon) as max_radon, AVG(radon) as avg_radon,
                MIN(timestamp) as min_ts, MAX(timestamp) as max_ts
             FROM history {}",
            where_clause
        );

        let params_refs: Vec<&dyn rusqlite::ToSql> = params.iter().map(|p| p.as_ref()).collect();

        let stats = self.conn.query_row(&sql, params_refs.as_slice(), |row| {
            let count: i64 = row.get(0)?;
            let min_ts: Option<i64> = row.get(16)?;
            let max_ts: Option<i64> = row.get(17)?;

            let time_range = match (min_ts, max_ts) {
                (Some(min), Some(max)) => {
                    Some((timestamp_from_unix(min), timestamp_from_unix(max)))
                }
                _ => None,
            };

            Ok(HistoryStats {
                count: count as u64,
                min: HistoryAggregates {
                    co2: row.get::<_, Option<i64>>(1)?.map(|v| v as f64),
                    temperature: row.get(4)?,
                    pressure: row.get(7)?,
                    humidity: row.get::<_, Option<i64>>(10)?.map(|v| v as f64),
                    radon: row.get::<_, Option<i64>>(13)?.map(|v| v as f64),
                },
                max: HistoryAggregates {
                    co2: row.get::<_, Option<i64>>(2)?.map(|v| v as f64),
                    temperature: row.get(5)?,
                    pressure: row.get(8)?,
                    humidity: row.get::<_, Option<i64>>(11)?.map(|v| v as f64),
                    radon: row.get::<_, Option<i64>>(14)?.map(|v| v as f64),
                },
                avg: HistoryAggregates {
                    co2: row.get(3)?,
                    temperature: row.get(6)?,
                    pressure: row.get(9)?,
                    humidity: row.get(12)?,
                    radon: row.get(15)?,
                },
                time_range,
            })
        })?;

        Ok(stats)
    }

    /// Export history records to CSV format.
    ///
    /// Exports records matching the query to a CSV string with the following columns:
    /// `timestamp`, `device_id`, `co2`, `temperature`, `pressure`, `humidity`, `radon`.
    ///
    /// Timestamps are formatted as RFC 3339 (e.g., `2024-01-15T10:30:00Z`).
    ///
    /// # Arguments
    ///
    /// * `query` - Filter which records to export
    ///
    /// # Example
    ///
    /// ```
    /// use aranet_store::{Store, HistoryQuery};
    /// use std::fs;
    ///
    /// let store = Store::open_in_memory()?;
    ///
    /// let query = HistoryQuery::new().device("Aranet4 17C3C").oldest_first();
    /// let csv = store.export_history_csv(&query)?;
    ///
    /// // Write to file
    /// // fs::write("history.csv", &csv)?;
    /// # Ok::<(), aranet_store::Error>(())
    /// ```
    pub fn export_history_csv(&self, query: &HistoryQuery) -> Result<String> {
        let records = self.query_history(query)?;
        let mut output = String::new();

        // Header
        output.push_str("timestamp,device_id,co2,temperature,pressure,humidity,radon\n");

        // Data rows
        for record in records {
            let timestamp = record
                .timestamp
                .format(&time::format_description::well_known::Rfc3339)
                .unwrap_or_default();
            let radon = record.radon.map(|r| r.to_string()).unwrap_or_default();

            output.push_str(&format!(
                "{},{},{},{:.1},{:.2},{},{}\n",
                timestamp,
                record.device_id,
                record.co2,
                record.temperature,
                record.pressure,
                record.humidity,
                radon
            ));
        }

        Ok(output)
    }

    /// Export history records to JSON format.
    ///
    /// Exports records matching the query as a pretty-printed JSON array of
    /// [`StoredHistoryRecord`] objects.
    ///
    /// # Arguments
    ///
    /// * `query` - Filter which records to export
    ///
    /// # Example
    ///
    /// ```
    /// use aranet_store::{Store, HistoryQuery};
    ///
    /// let store = Store::open_in_memory()?;
    ///
    /// let query = HistoryQuery::new().device("Aranet4 17C3C");
    /// let json = store.export_history_json(&query)?;
    /// println!("{}", json);
    /// # Ok::<(), aranet_store::Error>(())
    /// ```
    pub fn export_history_json(&self, query: &HistoryQuery) -> Result<String> {
        let records = self.query_history(query)?;
        let json = serde_json::to_string_pretty(&records)
            .map_err(|e| Error::Database(rusqlite::Error::ToSqlConversionFailure(Box::new(e))))?;
        Ok(json)
    }

    /// Import history records from CSV format.
    ///
    /// Expected CSV format:
    /// ```csv
    /// timestamp,device_id,co2,temperature,pressure,humidity,radon
    /// 2024-01-15T10:30:00Z,Aranet4 17C3C,800,22.5,1013.25,45,
    /// ```
    ///
    /// Returns the number of records imported (deduplicated by device_id + timestamp).
    pub fn import_history_csv(&self, csv_data: &str) -> Result<ImportResult> {
        let mut reader = csv::ReaderBuilder::new()
            .has_headers(true)
            .flexible(true)
            .trim(csv::Trim::All)
            .from_reader(csv_data.as_bytes());

        let mut total = 0;
        let mut imported = 0;
        let mut skipped = 0;
        let mut errors = Vec::new();

        // Track devices we've already upserted to avoid N+1 queries
        let mut upserted_devices = std::collections::HashSet::new();

        for (line_num, result) in reader.records().enumerate() {
            total += 1;
            let line = line_num + 2; // Account for header and 0-indexing

            let record = match result {
                Ok(r) => r,
                Err(e) => {
                    errors.push(format!("Line {}: parse error - {}", line, e));
                    skipped += 1;
                    continue;
                }
            };

            // Parse fields
            let timestamp_str = record.get(0).unwrap_or("").trim();
            let device_id = record.get(1).unwrap_or("").trim();
            let co2_str = record.get(2).unwrap_or("").trim();
            let temp_str = record.get(3).unwrap_or("").trim();
            let pressure_str = record.get(4).unwrap_or("").trim();
            let humidity_str = record.get(5).unwrap_or("").trim();
            let radon_str = record.get(6).unwrap_or("").trim();

            // Validate required fields
            if device_id.is_empty() {
                errors.push(format!("Line {}: missing device_id", line));
                skipped += 1;
                continue;
            }

            // Parse timestamp
            let timestamp = match OffsetDateTime::parse(
                timestamp_str,
                &time::format_description::well_known::Rfc3339,
            ) {
                Ok(ts) => ts,
                Err(_) => {
                    errors.push(format!(
                        "Line {}: invalid timestamp '{}'",
                        line, timestamp_str
                    ));
                    skipped += 1;
                    continue;
                }
            };

            // Parse numeric fields with defaults and validation
            let co2: u16 = match co2_str.parse::<u16>() {
                Ok(v) if v <= 10000 => v, // CO2 sensor max is typically 10000 ppm
                Ok(v) => {
                    errors.push(format!(
                        "Line {}: CO2 value {} exceeds maximum of 10000 ppm",
                        line, v
                    ));
                    skipped += 1;
                    continue;
                }
                Err(_) if co2_str.is_empty() => 0,
                Err(_) => {
                    errors.push(format!("Line {}: invalid CO2 value '{}'", line, co2_str));
                    skipped += 1;
                    continue;
                }
            };

            let temperature: f32 = match temp_str.parse::<f32>() {
                Ok(v) if (-40.0..=100.0).contains(&v) => v,
                Ok(v) => {
                    errors.push(format!(
                        "Line {}: temperature {} is outside valid range (-40 to 100°C)",
                        line, v
                    ));
                    skipped += 1;
                    continue;
                }
                Err(_) if temp_str.is_empty() => 0.0,
                Err(_) => {
                    errors.push(format!(
                        "Line {}: invalid temperature value '{}'",
                        line, temp_str
                    ));
                    skipped += 1;
                    continue;
                }
            };

            let pressure: f32 = match pressure_str.parse::<f32>() {
                Ok(v) if v == 0.0 || (800.0..=1200.0).contains(&v) => v,
                Ok(v) => {
                    errors.push(format!(
                        "Line {}: pressure {} is outside valid range (800-1200 hPa)",
                        line, v
                    ));
                    skipped += 1;
                    continue;
                }
                Err(_) if pressure_str.is_empty() => 0.0,
                Err(_) => {
                    errors.push(format!(
                        "Line {}: invalid pressure value '{}'",
                        line, pressure_str
                    ));
                    skipped += 1;
                    continue;
                }
            };

            let humidity: u8 = match humidity_str.parse::<u8>() {
                Ok(v) if v <= 100 => v,
                Ok(v) => {
                    errors.push(format!(
                        "Line {}: humidity {} exceeds maximum of 100%",
                        line, v
                    ));
                    skipped += 1;
                    continue;
                }
                Err(_) if humidity_str.is_empty() => 0,
                Err(_) => {
                    errors.push(format!(
                        "Line {}: invalid humidity value '{}'",
                        line, humidity_str
                    ));
                    skipped += 1;
                    continue;
                }
            };

            let radon: Option<u32> = if radon_str.is_empty() {
                None
            } else {
                match radon_str.parse::<u32>() {
                    Ok(v) if v <= 100000 => Some(v), // Radon max ~100000 Bq/m³
                    Ok(v) => {
                        errors.push(format!(
                            "Line {}: radon value {} exceeds maximum of 100000 Bq/m³",
                            line, v
                        ));
                        skipped += 1;
                        continue;
                    }
                    Err(_) => {
                        errors.push(format!(
                            "Line {}: invalid radon value '{}'",
                            line, radon_str
                        ));
                        skipped += 1;
                        continue;
                    }
                }
            };

            // Create history record
            let history_record = HistoryRecord {
                timestamp,
                co2,
                temperature,
                pressure,
                humidity,
                radon,
                radiation_rate: None,
                radiation_total: None,
            };

            // Ensure device exists (only once per unique device_id)
            if upserted_devices.insert(device_id.to_string()) {
                self.upsert_device(device_id, None)?;
            }
            let count = self.insert_history(device_id, &[history_record])?;
            imported += count;
            if count == 0 {
                skipped += 1; // Duplicate record
            }
        }

        Ok(ImportResult {
            total,
            imported,
            skipped,
            errors,
        })
    }

    /// Import history records from JSON format.
    ///
    /// Expected JSON format: an array of StoredHistoryRecord objects.
    ///
    /// Returns the number of records imported (deduplicated by device_id + timestamp).
    pub fn import_history_json(&self, json_data: &str) -> Result<ImportResult> {
        let records: Vec<StoredHistoryRecord> = serde_json::from_str(json_data)
            .map_err(|e| Error::Database(rusqlite::Error::ToSqlConversionFailure(Box::new(e))))?;

        let total = records.len();
        let mut imported = 0;
        let mut skipped = 0;

        // Track devices we've already upserted to avoid N+1 queries
        let mut upserted_devices = std::collections::HashSet::new();

        for record in records {
            // Convert to HistoryRecord
            let history_record = record.to_history();

            // Ensure device exists (only once per unique device_id)
            if upserted_devices.insert(record.device_id.clone()) {
                self.upsert_device(&record.device_id, None)?;
            }
            let count = self.insert_history(&record.device_id, &[history_record])?;
            imported += count;
            if count == 0 {
                skipped += 1; // Duplicate record
            }
        }

        Ok(ImportResult {
            total,
            imported,
            skipped,
            errors: Vec::new(),
        })
    }
}

/// Result of an import operation.
#[derive(Debug, Clone)]
pub struct ImportResult {
    /// Total records processed.
    pub total: usize,
    /// Records successfully imported.
    pub imported: usize,
    /// Records skipped (duplicates or errors).
    pub skipped: usize,
    /// Error messages for failed records.
    pub errors: Vec<String>,
}

#[cfg(test)]
mod tests {
    use super::*;
    use aranet_types::Status;

    fn create_test_reading() -> CurrentReading {
        CurrentReading {
            co2: 800,
            temperature: 22.5,
            pressure: 1013.0,
            humidity: 45,
            battery: 85,
            status: Status::Green,
            interval: 60,
            age: 30,
            captured_at: Some(OffsetDateTime::now_utc()),
            radon: None,
            radiation_rate: None,
            radiation_total: None,
            radon_avg_24h: None,
            radon_avg_7d: None,
            radon_avg_30d: None,
        }
    }

    #[test]
    fn test_open_in_memory() {
        let store = Store::open_in_memory().unwrap();
        let devices = store.list_devices().unwrap();
        assert!(devices.is_empty());
    }

    #[test]
    fn test_upsert_device() {
        let store = Store::open_in_memory().unwrap();

        let device = store.upsert_device("test-device", Some("Test")).unwrap();
        assert_eq!(device.id, "test-device");
        assert_eq!(device.name, Some("Test".to_string()));

        // Update name
        let device = store
            .upsert_device("test-device", Some("New Name"))
            .unwrap();
        assert_eq!(device.name, Some("New Name".to_string()));
    }

    #[test]
    fn test_insert_and_query_reading() {
        let store = Store::open_in_memory().unwrap();
        let reading = create_test_reading();

        store.insert_reading("test-device", &reading).unwrap();

        let query = ReadingQuery::new().device("test-device");
        let readings = store.query_readings(&query).unwrap();

        assert_eq!(readings.len(), 1);
        assert_eq!(readings[0].co2, 800);
        assert_eq!(readings[0].temperature, 22.5);
    }

    #[test]
    fn test_get_latest_reading() {
        let store = Store::open_in_memory().unwrap();

        let mut reading1 = create_test_reading();
        reading1.co2 = 700;
        store.insert_reading("test-device", &reading1).unwrap();

        let mut reading2 = create_test_reading();
        reading2.co2 = 900;
        store.insert_reading("test-device", &reading2).unwrap();

        let latest = store.get_latest_reading("test-device").unwrap().unwrap();
        assert_eq!(latest.co2, 900);
    }

    #[test]
    fn test_insert_history_deduplication() {
        let store = Store::open_in_memory().unwrap();

        let now = OffsetDateTime::now_utc();
        let records = vec![
            HistoryRecord {
                timestamp: now,
                co2: 800,
                temperature: 22.0,
                pressure: 1013.0,
                humidity: 45,
                radon: None,
                radiation_rate: None,
                radiation_total: None,
            },
            HistoryRecord {
                timestamp: now, // Same timestamp - should be deduplicated
                co2: 850,
                temperature: 23.0,
                pressure: 1014.0,
                humidity: 46,
                radon: None,
                radiation_rate: None,
                radiation_total: None,
            },
        ];

        let inserted = store.insert_history("test-device", &records).unwrap();
        assert_eq!(inserted, 1); // Only one inserted due to dedup

        let count = store.count_history(Some("test-device")).unwrap();
        assert_eq!(count, 1);
    }

    #[test]
    fn test_sync_state() {
        let store = Store::open_in_memory().unwrap();
        store.upsert_device("test-device", None).unwrap();

        // Initially no sync state
        let state = store.get_sync_state("test-device").unwrap();
        assert!(state.is_none());

        // Update sync state
        store.update_sync_state("test-device", 100, 100).unwrap();

        let state = store.get_sync_state("test-device").unwrap().unwrap();
        assert_eq!(state.last_history_index, Some(100));
        assert_eq!(state.total_readings, Some(100));
        assert!(state.last_sync_at.is_some());
    }

    #[test]
    fn test_calculate_sync_start() {
        let store = Store::open_in_memory().unwrap();
        store.upsert_device("test-device", None).unwrap();

        // First sync - should start from 1
        let start = store.calculate_sync_start("test-device", 100).unwrap();
        assert_eq!(start, 1);

        // Simulate syncing: insert history records and update state
        let now = OffsetDateTime::now_utc();
        let records = vec![HistoryRecord {
            timestamp: now,
            co2: 800,
            temperature: 22.0,
            pressure: 1013.0,
            humidity: 45,
            radon: None,
            radiation_rate: None,
            radiation_total: None,
        }];
        store.insert_history("test-device", &records).unwrap();
        store.update_sync_state("test-device", 100, 100).unwrap();

        // No new readings and recent history exists - should return beyond range
        let start = store.calculate_sync_start("test-device", 100).unwrap();
        assert_eq!(start, 101);

        // New readings added - should start from 101
        let start = store.calculate_sync_start("test-device", 110).unwrap();
        assert_eq!(start, 101);
    }

    #[test]
    fn test_calculate_sync_start_cache_cleared() {
        let store = Store::open_in_memory().unwrap();
        store.upsert_device("test-device", None).unwrap();

        // Simulate previous sync
        store.update_sync_state("test-device", 100, 100).unwrap();

        // No history records exist (cache was cleared) - should do full sync
        let start = store.calculate_sync_start("test-device", 100).unwrap();
        assert_eq!(start, 1);
    }

    #[test]
    fn test_calculate_sync_start_buffer_wrapped() {
        let store = Store::open_in_memory().unwrap();
        store.upsert_device("test-device", None).unwrap();

        // Insert an old history record (more than 10 min ago)
        let old_time = OffsetDateTime::now_utc() - time::Duration::minutes(30);
        let records = vec![HistoryRecord {
            timestamp: old_time,
            co2: 800,
            temperature: 22.0,
            pressure: 1013.0,
            humidity: 45,
            radon: None,
            radiation_rate: None,
            radiation_total: None,
        }];
        store.insert_history("test-device", &records).unwrap();
        store.update_sync_state("test-device", 100, 100).unwrap();

        // Device still shows 100 readings but latest record is old
        // This indicates buffer may have wrapped - should do full sync
        let start = store.calculate_sync_start("test-device", 100).unwrap();
        assert_eq!(start, 1);
    }

    #[test]
    fn test_calculate_sync_start_index_overflow() {
        let store = Store::open_in_memory().unwrap();
        store.upsert_device("test-device", None).unwrap();

        // Simulate state where last_index exceeds current_total (buffer reset)
        store.update_sync_state("test-device", 500, 500).unwrap();

        // Device was reset and now has fewer readings
        // start would be 501 which exceeds 200, should do full sync
        let start = store.calculate_sync_start("test-device", 200).unwrap();
        assert_eq!(start, 1);
    }

    #[test]
    fn test_import_history_csv() {
        let store = Store::open_in_memory().unwrap();

        let csv_data = r#"timestamp,device_id,co2,temperature,pressure,humidity,radon
2024-01-15T10:30:00Z,Aranet4 17C3C,800,22.5,1013.25,45,
2024-01-15T11:30:00Z,Aranet4 17C3C,850,23.0,1014.00,48,
2024-01-15T12:30:00Z,AranetRn+ 306B8,0,21.0,1012.00,50,150
"#;

        let result = store.import_history_csv(csv_data).unwrap();

        assert_eq!(result.total, 3);
        assert_eq!(result.imported, 3);
        assert_eq!(result.skipped, 0);
        assert!(result.errors.is_empty());

        // Verify data was imported
        let devices = store.list_devices().unwrap();
        assert_eq!(devices.len(), 2);

        // Query defaults to newest_first=true (DESC order)
        let query = HistoryQuery::new().device("Aranet4 17C3C");
        let records = store.query_history(&query).unwrap();
        assert_eq!(records.len(), 2);
        assert_eq!(records[0].co2, 850); // 11:30 - newest first
        assert_eq!(records[1].co2, 800); // 10:30 - oldest

        // Verify radon device
        let query = HistoryQuery::new().device("AranetRn+ 306B8");
        let records = store.query_history(&query).unwrap();
        assert_eq!(records.len(), 1);
        assert_eq!(records[0].radon, Some(150));
    }

    #[test]
    fn test_import_history_csv_deduplication() {
        let store = Store::open_in_memory().unwrap();

        let csv_data = r#"timestamp,device_id,co2,temperature,pressure,humidity,radon
2024-01-15T10:30:00Z,test-device,800,22.5,1013.25,45,
"#;

        // Import once
        let result = store.import_history_csv(csv_data).unwrap();
        assert_eq!(result.imported, 1);

        // Import again - should skip duplicate
        let result = store.import_history_csv(csv_data).unwrap();
        assert_eq!(result.imported, 0);
        assert_eq!(result.skipped, 1);
    }

    #[test]
    fn test_import_history_csv_with_errors() {
        let store = Store::open_in_memory().unwrap();

        let csv_data = r#"timestamp,device_id,co2,temperature,pressure,humidity,radon
invalid-timestamp,test-device,800,22.5,1013.25,45,
2024-01-15T10:30:00Z,,800,22.5,1013.25,45,
2024-01-15T11:30:00Z,valid-device,900,23.0,1014.00,50,
"#;

        let result = store.import_history_csv(csv_data).unwrap();

        assert_eq!(result.total, 3);
        assert_eq!(result.imported, 1);
        assert_eq!(result.skipped, 2);
        assert_eq!(result.errors.len(), 2);
    }

    #[test]
    fn test_import_history_json() {
        let store = Store::open_in_memory().unwrap();

        let json_data = r#"[
            {
                "id": 0,
                "device_id": "Aranet4 17C3C",
                "timestamp": "2024-01-15T10:30:00Z",
                "synced_at": "2024-01-15T12:00:00Z",
                "co2": 800,
                "temperature": 22.5,
                "pressure": 1013.25,
                "humidity": 45,
                "radon": null,
                "radiation_rate": null,
                "radiation_total": null
            },
            {
                "id": 0,
                "device_id": "Aranet4 17C3C",
                "timestamp": "2024-01-15T11:30:00Z",
                "synced_at": "2024-01-15T12:00:00Z",
                "co2": 850,
                "temperature": 23.0,
                "pressure": 1014.0,
                "humidity": 48,
                "radon": null,
                "radiation_rate": null,
                "radiation_total": null
            }
        ]"#;

        let result = store.import_history_json(json_data).unwrap();

        assert_eq!(result.total, 2);
        assert_eq!(result.imported, 2);
        assert_eq!(result.skipped, 0);

        // Verify data was imported
        let query = HistoryQuery::new().device("Aranet4 17C3C");
        let records = store.query_history(&query).unwrap();
        assert_eq!(records.len(), 2);
    }

    // ==================== History Stats Tests ====================

    #[test]
    fn test_history_stats_empty() {
        let store = Store::open_in_memory().unwrap();

        let query = HistoryQuery::new();
        let stats = store.history_stats(&query).unwrap();

        assert_eq!(stats.count, 0);
        assert!(stats.min.co2.is_none());
        assert!(stats.max.co2.is_none());
        assert!(stats.avg.co2.is_none());
        assert!(stats.time_range.is_none());
    }

    #[test]
    fn test_history_stats_single_record() {
        let store = Store::open_in_memory().unwrap();

        let now = OffsetDateTime::now_utc();
        let records = vec![HistoryRecord {
            timestamp: now,
            co2: 800,
            temperature: 22.5,
            pressure: 1013.0,
            humidity: 45,
            radon: None,
            radiation_rate: None,
            radiation_total: None,
        }];

        store.insert_history("test-device", &records).unwrap();

        let query = HistoryQuery::new();
        let stats = store.history_stats(&query).unwrap();

        assert_eq!(stats.count, 1);
        assert_eq!(stats.min.co2, Some(800.0));
        assert_eq!(stats.max.co2, Some(800.0));
        assert_eq!(stats.avg.co2, Some(800.0));
        assert_eq!(stats.min.temperature, Some(22.5));
        assert_eq!(stats.max.temperature, Some(22.5));
    }

    #[test]
    fn test_history_stats_multiple_records() {
        let store = Store::open_in_memory().unwrap();

        let base_time = OffsetDateTime::now_utc();
        let records = vec![
            HistoryRecord {
                timestamp: base_time,
                co2: 600,
                temperature: 20.0,
                pressure: 1010.0,
                humidity: 40,
                radon: None,
                radiation_rate: None,
                radiation_total: None,
            },
            HistoryRecord {
                timestamp: base_time + time::Duration::hours(1),
                co2: 800,
                temperature: 22.0,
                pressure: 1012.0,
                humidity: 50,
                radon: None,
                radiation_rate: None,
                radiation_total: None,
            },
            HistoryRecord {
                timestamp: base_time + time::Duration::hours(2),
                co2: 1000,
                temperature: 24.0,
                pressure: 1014.0,
                humidity: 60,
                radon: None,
                radiation_rate: None,
                radiation_total: None,
            },
        ];

        store.insert_history("test-device", &records).unwrap();

        let query = HistoryQuery::new();
        let stats = store.history_stats(&query).unwrap();

        assert_eq!(stats.count, 3);
        assert_eq!(stats.min.co2, Some(600.0));
        assert_eq!(stats.max.co2, Some(1000.0));
        assert_eq!(stats.avg.co2, Some(800.0));
        assert_eq!(stats.min.temperature, Some(20.0));
        assert_eq!(stats.max.temperature, Some(24.0));
        assert_eq!(stats.avg.humidity, Some(50.0));
    }

    #[test]
    fn test_history_stats_with_device_filter() {
        let store = Store::open_in_memory().unwrap();

        let now = OffsetDateTime::now_utc();

        // Device 1 - high CO2
        store
            .insert_history(
                "device-1",
                &[HistoryRecord {
                    timestamp: now,
                    co2: 1200,
                    temperature: 25.0,
                    pressure: 1015.0,
                    humidity: 55,
                    radon: None,
                    radiation_rate: None,
                    radiation_total: None,
                }],
            )
            .unwrap();

        // Device 2 - low CO2
        store
            .insert_history(
                "device-2",
                &[HistoryRecord {
                    timestamp: now,
                    co2: 400,
                    temperature: 18.0,
                    pressure: 1010.0,
                    humidity: 35,
                    radon: None,
                    radiation_rate: None,
                    radiation_total: None,
                }],
            )
            .unwrap();

        // Stats for device 1 only
        let query = HistoryQuery::new().device("device-1");
        let stats = store.history_stats(&query).unwrap();

        assert_eq!(stats.count, 1);
        assert_eq!(stats.avg.co2, Some(1200.0));
    }

    #[test]
    fn test_history_stats_with_time_range() {
        let store = Store::open_in_memory().unwrap();

        let base_time = OffsetDateTime::now_utc();
        let records = vec![
            HistoryRecord {
                timestamp: base_time - time::Duration::days(2),
                co2: 500,
                temperature: 19.0,
                pressure: 1008.0,
                humidity: 40,
                radon: None,
                radiation_rate: None,
                radiation_total: None,
            },
            HistoryRecord {
                timestamp: base_time,
                co2: 800,
                temperature: 22.0,
                pressure: 1012.0,
                humidity: 50,
                radon: None,
                radiation_rate: None,
                radiation_total: None,
            },
        ];

        store.insert_history("test-device", &records).unwrap();

        // Query only recent records
        let query = HistoryQuery::new().since(base_time - time::Duration::hours(1));
        let stats = store.history_stats(&query).unwrap();

        assert_eq!(stats.count, 1);
        assert_eq!(stats.avg.co2, Some(800.0));
    }

    #[test]
    fn test_history_stats_with_radon() {
        let store = Store::open_in_memory().unwrap();

        let now = OffsetDateTime::now_utc();
        let records = vec![
            HistoryRecord {
                timestamp: now,
                co2: 0,
                temperature: 20.0,
                pressure: 1010.0,
                humidity: 50,
                radon: Some(100),
                radiation_rate: None,
                radiation_total: None,
            },
            HistoryRecord {
                timestamp: now + time::Duration::hours(1),
                co2: 0,
                temperature: 20.0,
                pressure: 1010.0,
                humidity: 50,
                radon: Some(200),
                radiation_rate: None,
                radiation_total: None,
            },
        ];

        store.insert_history("radon-device", &records).unwrap();

        let query = HistoryQuery::new();
        let stats = store.history_stats(&query).unwrap();

        assert_eq!(stats.count, 2);
        assert_eq!(stats.min.radon, Some(100.0));
        assert_eq!(stats.max.radon, Some(200.0));
        assert_eq!(stats.avg.radon, Some(150.0));
    }

    #[test]
    fn test_history_stats_time_range_values() {
        let store = Store::open_in_memory().unwrap();

        // Use fixed timestamps to avoid precision issues with unix timestamp conversion
        use time::macros::datetime;
        let start = datetime!(2024-01-01 00:00:00 UTC);
        let end = datetime!(2024-01-08 00:00:00 UTC);

        let records = vec![
            HistoryRecord {
                timestamp: start,
                co2: 700,
                temperature: 21.0,
                pressure: 1011.0,
                humidity: 45,
                radon: None,
                radiation_rate: None,
                radiation_total: None,
            },
            HistoryRecord {
                timestamp: end,
                co2: 900,
                temperature: 23.0,
                pressure: 1013.0,
                humidity: 55,
                radon: None,
                radiation_rate: None,
                radiation_total: None,
            },
        ];

        store.insert_history("test-device", &records).unwrap();

        let query = HistoryQuery::new();
        let stats = store.history_stats(&query).unwrap();

        let (min_ts, max_ts) = stats.time_range.unwrap();
        assert_eq!(min_ts, start);
        assert_eq!(max_ts, end);
    }

    // ==================== Export Tests ====================

    #[test]
    fn test_export_history_csv_empty() {
        let store = Store::open_in_memory().unwrap();

        let query = HistoryQuery::new();
        let csv = store.export_history_csv(&query).unwrap();

        assert!(csv.starts_with("timestamp,device_id,co2,temperature,pressure,humidity,radon\n"));
        // Only header, no data
        assert_eq!(csv.lines().count(), 1);
    }

    #[test]
    fn test_export_history_csv_with_data() {
        let store = Store::open_in_memory().unwrap();

        let csv_data = r#"timestamp,device_id,co2,temperature,pressure,humidity,radon
2024-01-15T10:30:00Z,test-device,800,22.5,1013.25,45,
"#;
        store.import_history_csv(csv_data).unwrap();

        let query = HistoryQuery::new();
        let csv = store.export_history_csv(&query).unwrap();

        assert!(csv.contains("test-device"));
        assert!(csv.contains("800"));
        assert!(csv.contains("22.5"));
        assert!(csv.contains("1013.25"));
        assert!(csv.contains("45"));
    }

    #[test]
    fn test_export_history_csv_with_radon() {
        let store = Store::open_in_memory().unwrap();

        let now = OffsetDateTime::now_utc();
        let records = vec![HistoryRecord {
            timestamp: now,
            co2: 0,
            temperature: 20.0,
            pressure: 1010.0,
            humidity: 50,
            radon: Some(150),
            radiation_rate: None,
            radiation_total: None,
        }];

        store.insert_history("radon-device", &records).unwrap();

        let query = HistoryQuery::new();
        let csv = store.export_history_csv(&query).unwrap();

        assert!(csv.contains("150"));
    }

    #[test]
    fn test_export_history_csv_format() {
        let store = Store::open_in_memory().unwrap();

        let csv_data = r#"timestamp,device_id,co2,temperature,pressure,humidity,radon
2024-01-15T10:30:00Z,device-1,800,22.5,1013.25,45,
2024-01-15T11:30:00Z,device-1,850,23.0,1014.00,48,
"#;
        store.import_history_csv(csv_data).unwrap();

        let query = HistoryQuery::new().oldest_first();
        let csv = store.export_history_csv(&query).unwrap();

        let lines: Vec<&str> = csv.lines().collect();
        assert_eq!(lines.len(), 3); // header + 2 records

        // Check header
        assert!(lines[0].contains("timestamp"));
        assert!(lines[0].contains("device_id"));
        assert!(lines[0].contains("co2"));

        // Check data ordering (oldest first)
        assert!(lines[1].contains("800"));
        assert!(lines[2].contains("850"));
    }

    #[test]
    fn test_export_history_json_empty() {
        let store = Store::open_in_memory().unwrap();

        let query = HistoryQuery::new();
        let json = store.export_history_json(&query).unwrap();

        assert_eq!(json.trim(), "[]");
    }

    #[test]
    fn test_export_history_json_with_data() {
        let store = Store::open_in_memory().unwrap();

        let now = OffsetDateTime::now_utc();
        let records = vec![HistoryRecord {
            timestamp: now,
            co2: 800,
            temperature: 22.5,
            pressure: 1013.0,
            humidity: 45,
            radon: None,
            radiation_rate: None,
            radiation_total: None,
        }];

        store.insert_history("test-device", &records).unwrap();

        let query = HistoryQuery::new();
        let json = store.export_history_json(&query).unwrap();

        // Parse and verify
        let parsed: Vec<serde_json::Value> = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.len(), 1);
        assert_eq!(parsed[0]["device_id"], "test-device");
        assert_eq!(parsed[0]["co2"], 800);
    }

    #[test]
    fn test_export_import_json_roundtrip() {
        let store = Store::open_in_memory().unwrap();

        let now = OffsetDateTime::now_utc();
        let original_records = vec![
            HistoryRecord {
                timestamp: now,
                co2: 750,
                temperature: 21.5,
                pressure: 1012.0,
                humidity: 48,
                radon: None,
                radiation_rate: None,
                radiation_total: None,
            },
            HistoryRecord {
                timestamp: now + time::Duration::hours(1),
                co2: 850,
                temperature: 22.5,
                pressure: 1013.0,
                humidity: 52,
                radon: None,
                radiation_rate: None,
                radiation_total: None,
            },
        ];

        store
            .insert_history("roundtrip-device", &original_records)
            .unwrap();

        // Export
        let query = HistoryQuery::new()
            .device("roundtrip-device")
            .oldest_first();
        let json = store.export_history_json(&query).unwrap();

        // Create new store and import
        let store2 = Store::open_in_memory().unwrap();
        let result = store2.import_history_json(&json).unwrap();

        assert_eq!(result.imported, 2);

        // Verify data matches
        let records = store2.query_history(&query).unwrap();
        assert_eq!(records.len(), 2);
        assert_eq!(records[0].co2, 750);
        assert_eq!(records[1].co2, 850);
    }

    // ==================== Query Tests ====================

    #[test]
    fn test_query_readings_with_pagination() {
        let store = Store::open_in_memory().unwrap();

        // Insert 10 readings
        for i in 0..10 {
            let mut reading = create_test_reading();
            reading.co2 = 700 + i * 10;
            store.insert_reading("paginated-device", &reading).unwrap();
        }

        // Query with limit and offset
        let query = ReadingQuery::new()
            .device("paginated-device")
            .oldest_first()
            .limit(3)
            .offset(2);

        let readings = store.query_readings(&query).unwrap();
        assert_eq!(readings.len(), 3);
        assert_eq!(readings[0].co2, 720); // 3rd reading (offset 2)
        assert_eq!(readings[2].co2, 740); // 5th reading
    }

    #[test]
    fn test_query_readings_time_range() {
        let store = Store::open_in_memory().unwrap();

        let base_time = OffsetDateTime::now_utc();

        // Insert readings at different times
        let mut reading1 = create_test_reading();
        reading1.captured_at = Some(base_time - time::Duration::days(2));
        reading1.co2 = 600;
        store.insert_reading("time-device", &reading1).unwrap();

        let mut reading2 = create_test_reading();
        reading2.captured_at = Some(base_time - time::Duration::hours(1));
        reading2.co2 = 800;
        store.insert_reading("time-device", &reading2).unwrap();

        let mut reading3 = create_test_reading();
        reading3.captured_at = Some(base_time);
        reading3.co2 = 900;
        store.insert_reading("time-device", &reading3).unwrap();

        // Query last day only
        let query = ReadingQuery::new()
            .device("time-device")
            .since(base_time - time::Duration::days(1));

        let readings = store.query_readings(&query).unwrap();
        assert_eq!(readings.len(), 2);
    }

    #[test]
    fn test_query_history_with_pagination() {
        let store = Store::open_in_memory().unwrap();

        let base_time = OffsetDateTime::now_utc();
        let records: Vec<_> = (0..10)
            .map(|i| HistoryRecord {
                timestamp: base_time + time::Duration::hours(i),
                co2: 700 + (i as u16) * 10,
                temperature: 22.0,
                pressure: 1013.0,
                humidity: 50,
                radon: None,
                radiation_rate: None,
                radiation_total: None,
            })
            .collect();

        store.insert_history("paginated-device", &records).unwrap();

        // Query with limit and offset
        let query = HistoryQuery::new()
            .device("paginated-device")
            .oldest_first()
            .limit(3)
            .offset(2);

        let results = store.query_history(&query).unwrap();
        assert_eq!(results.len(), 3);
        assert_eq!(results[0].co2, 720);
        assert_eq!(results[2].co2, 740);
    }

    // ==================== Device Tests ====================

    #[test]
    fn test_update_device_info() {
        let store = Store::open_in_memory().unwrap();
        store.upsert_device("info-device", None).unwrap();

        let info = aranet_types::DeviceInfo {
            name: "My Aranet4".to_string(),
            model: "Aranet4".to_string(),
            serial: "ABC123".to_string(),
            firmware: "v1.2.0".to_string(),
            hardware: "1.0".to_string(),
            ..Default::default()
        };

        store.update_device_info("info-device", &info).unwrap();

        let device = store.get_device("info-device").unwrap().unwrap();
        assert_eq!(device.name, Some("My Aranet4".to_string()));
        assert_eq!(device.serial, Some("ABC123".to_string()));
        assert_eq!(device.firmware, Some("v1.2.0".to_string()));
        assert_eq!(device.device_type, Some(aranet_types::DeviceType::Aranet4));
    }

    #[test]
    fn test_update_device_info_aranet2() {
        let store = Store::open_in_memory().unwrap();
        store.upsert_device("aranet2-device", None).unwrap();

        let info = aranet_types::DeviceInfo {
            name: "My Aranet2".to_string(),
            model: "Aranet2".to_string(),
            serial: "XYZ789".to_string(),
            firmware: "v2.0.0".to_string(),
            hardware: "2.0".to_string(),
            ..Default::default()
        };

        store.update_device_info("aranet2-device", &info).unwrap();

        let device = store.get_device("aranet2-device").unwrap().unwrap();
        assert_eq!(device.device_type, Some(aranet_types::DeviceType::Aranet2));
    }

    #[test]
    fn test_update_device_info_radon() {
        let store = Store::open_in_memory().unwrap();
        store.upsert_device("radon-device", None).unwrap();

        let info = aranet_types::DeviceInfo {
            name: "My AranetRn+".to_string(),
            model: "AranetRn+ Radon".to_string(),
            serial: "RAD001".to_string(),
            firmware: "v1.0.0".to_string(),
            hardware: "1.0".to_string(),
            ..Default::default()
        };

        store.update_device_info("radon-device", &info).unwrap();

        let device = store.get_device("radon-device").unwrap().unwrap();
        assert_eq!(
            device.device_type,
            Some(aranet_types::DeviceType::AranetRadon)
        );
    }

    #[test]
    fn test_update_device_metadata() {
        let store = Store::open_in_memory().unwrap();
        store.upsert_device("meta-device", None).unwrap();

        store
            .update_device_metadata(
                "meta-device",
                Some("Kitchen Sensor"),
                Some(aranet_types::DeviceType::Aranet4),
            )
            .unwrap();

        let device = store.get_device("meta-device").unwrap().unwrap();
        assert_eq!(device.name, Some("Kitchen Sensor".to_string()));
        assert_eq!(device.device_type, Some(aranet_types::DeviceType::Aranet4));
    }

    #[test]
    fn test_list_devices_ordered_by_last_seen() {
        let store = Store::open_in_memory().unwrap();

        // Insert devices and verify ordering
        // We'll use a longer sleep to ensure timestamp differences
        store.upsert_device("device-a", Some("First")).unwrap();
        std::thread::sleep(std::time::Duration::from_secs(1));
        store.upsert_device("device-b", Some("Second")).unwrap();
        std::thread::sleep(std::time::Duration::from_secs(1));
        store.upsert_device("device-c", Some("Third")).unwrap();

        let devices = store.list_devices().unwrap();
        assert_eq!(devices.len(), 3);

        // Verify devices are ordered by last_seen DESC (most recent first)
        // Since timestamps are stored as unix timestamps (seconds),
        // we need 1+ second sleep between inserts
        assert!(devices[0].last_seen >= devices[1].last_seen);
        assert!(devices[1].last_seen >= devices[2].last_seen);
    }

    #[test]
    fn test_count_readings() {
        let store = Store::open_in_memory().unwrap();

        // Insert readings for multiple devices
        for _ in 0..5 {
            store
                .insert_reading("device-1", &create_test_reading())
                .unwrap();
        }
        for _ in 0..3 {
            store
                .insert_reading("device-2", &create_test_reading())
                .unwrap();
        }

        // Count for specific device
        assert_eq!(store.count_readings(Some("device-1")).unwrap(), 5);
        assert_eq!(store.count_readings(Some("device-2")).unwrap(), 3);
        assert_eq!(store.count_readings(Some("nonexistent")).unwrap(), 0);

        // Count all
        assert_eq!(store.count_readings(None).unwrap(), 8);
    }

    #[test]
    fn test_count_history() {
        let store = Store::open_in_memory().unwrap();

        let now = OffsetDateTime::now_utc();

        // Insert history for multiple devices
        let records: Vec<_> = (0..5)
            .map(|i| HistoryRecord {
                timestamp: now + time::Duration::hours(i),
                co2: 800,
                temperature: 22.0,
                pressure: 1013.0,
                humidity: 50,
                radon: None,
                radiation_rate: None,
                radiation_total: None,
            })
            .collect();

        store.insert_history("device-1", &records).unwrap();
        store.insert_history("device-2", &records[..3]).unwrap();

        assert_eq!(store.count_history(Some("device-1")).unwrap(), 5);
        assert_eq!(store.count_history(Some("device-2")).unwrap(), 3);
        assert_eq!(store.count_history(None).unwrap(), 8);
    }

    // ==================== Edge Cases ====================

    #[test]
    fn test_reading_with_all_sensor_types() {
        let store = Store::open_in_memory().unwrap();

        // Aranet4 reading
        let reading = create_test_reading();
        store.insert_reading("aranet4", &reading).unwrap();

        // Radon reading
        let mut radon_reading = create_test_reading();
        radon_reading.co2 = 0;
        radon_reading.radon = Some(150);
        store.insert_reading("aranet-rn", &radon_reading).unwrap();

        // Radiation reading
        let mut rad_reading = create_test_reading();
        rad_reading.co2 = 0;
        rad_reading.radiation_rate = Some(0.12);
        rad_reading.radiation_total = Some(0.003);
        store.insert_reading("aranet-rad", &rad_reading).unwrap();

        // Query each device
        let aranet4_readings = store
            .query_readings(&ReadingQuery::new().device("aranet4"))
            .unwrap();
        assert_eq!(aranet4_readings.len(), 1);
        assert_eq!(aranet4_readings[0].co2, 800);

        let radon_readings = store
            .query_readings(&ReadingQuery::new().device("aranet-rn"))
            .unwrap();
        assert_eq!(radon_readings.len(), 1);
        assert_eq!(radon_readings[0].radon, Some(150));

        let rad_readings = store
            .query_readings(&ReadingQuery::new().device("aranet-rad"))
            .unwrap();
        assert_eq!(rad_readings.len(), 1);
        assert_eq!(rad_readings[0].radiation_rate, Some(0.12));
    }

    #[test]
    fn test_device_not_found_error() {
        let store = Store::open_in_memory().unwrap();

        // This should fail because the device doesn't exist
        // and we're not using upsert
        let result = store.get_device("nonexistent");
        assert!(result.unwrap().is_none());
    }

    #[test]
    fn test_empty_device_name() {
        let store = Store::open_in_memory().unwrap();

        // Empty name should be treated as None
        let info = aranet_types::DeviceInfo {
            name: "".to_string(),
            model: "Aranet4".to_string(),
            ..Default::default()
        };

        store.upsert_device("empty-name-device", None).unwrap();
        store
            .update_device_info("empty-name-device", &info)
            .unwrap();

        let device = store.get_device("empty-name-device").unwrap().unwrap();
        // Name should remain None since we passed empty string
        assert!(device.name.is_none());
    }

    #[test]
    fn test_import_csv_invalid_json() {
        let store = Store::open_in_memory().unwrap();

        let result = store.import_history_json("not valid json");
        assert!(result.is_err());
    }

    #[test]
    fn test_reading_with_all_status_types() {
        let store = Store::open_in_memory().unwrap();

        for status in [Status::Green, Status::Yellow, Status::Red, Status::Error] {
            let mut reading = create_test_reading();
            reading.status = status;
            let device_id = format!("status-{:?}", status);
            store.insert_reading(&device_id, &reading).unwrap();

            let stored = store.get_latest_reading(&device_id).unwrap().unwrap();
            assert_eq!(stored.status, status);
        }
    }

    // ==================== Concurrent Access Tests ====================
    //
    // These tests verify the store behaves correctly when accessed concurrently
    // through a Mutex, simulating the real-world usage in aranet-service.

    #[tokio::test]
    async fn test_concurrent_reading_inserts() {
        use std::sync::Arc;
        use tokio::sync::Mutex;

        let store = Arc::new(Mutex::new(Store::open_in_memory().unwrap()));

        // Spawn 10 concurrent tasks, each inserting 10 readings
        let mut handles = Vec::new();
        for task_id in 0..10 {
            let store = Arc::clone(&store);
            handles.push(tokio::spawn(async move {
                for i in 0..10 {
                    let reading = CurrentReading {
                        co2: 400 + (task_id * 100) + i,
                        temperature: 20.0 + (task_id as f32),
                        pressure: 1013.0,
                        humidity: 50,
                        battery: 85,
                        status: Status::Green,
                        interval: 60,
                        age: 0,
                        captured_at: Some(OffsetDateTime::now_utc()),
                        radon: None,
                        radiation_rate: None,
                        radiation_total: None,
                        radon_avg_24h: None,
                        radon_avg_7d: None,
                        radon_avg_30d: None,
                    };
                    let device_id = format!("concurrent-device-{}", task_id);
                    let guard = store.lock().await;
                    guard.insert_reading(&device_id, &reading).unwrap();
                }
            }));
        }

        // Wait for all tasks to complete
        for handle in handles {
            handle.await.unwrap();
        }

        // Verify all readings were inserted
        let guard = store.lock().await;
        let total = guard.count_readings(None).unwrap();
        assert_eq!(total, 100); // 10 tasks * 10 readings each
    }

    #[tokio::test]
    async fn test_concurrent_reads_and_writes() {
        use std::sync::Arc;
        use tokio::sync::Mutex;

        let store = Arc::new(Mutex::new(Store::open_in_memory().unwrap()));

        // Pre-populate with some data
        {
            let guard = store.lock().await;
            for i in 0..10 {
                let reading = CurrentReading {
                    co2: 500 + i * 50,
                    temperature: 22.0,
                    pressure: 1013.0,
                    humidity: 50,
                    battery: 85,
                    status: Status::Green,
                    interval: 60,
                    age: 0,
                    captured_at: Some(OffsetDateTime::now_utc()),
                    radon: None,
                    radiation_rate: None,
                    radiation_total: None,
                    radon_avg_24h: None,
                    radon_avg_7d: None,
                    radon_avg_30d: None,
                };
                guard.insert_reading("shared-device", &reading).unwrap();
            }
        }

        // Spawn concurrent readers and writers
        let mut handles = Vec::new();

        // 5 reader tasks
        for _ in 0..5 {
            let store = Arc::clone(&store);
            handles.push(tokio::spawn(async move {
                for _ in 0..10 {
                    let guard = store.lock().await;
                    let readings = guard
                        .query_readings(&ReadingQuery::new().device("shared-device"))
                        .unwrap();
                    assert!(!readings.is_empty());
                    drop(guard);
                    tokio::task::yield_now().await;
                }
            }));
        }

        // 3 writer tasks
        for task_id in 0..3 {
            let store = Arc::clone(&store);
            handles.push(tokio::spawn(async move {
                for i in 0..5 {
                    let reading = CurrentReading {
                        co2: 1000 + (task_id * 100) + i,
                        temperature: 25.0,
                        pressure: 1015.0,
                        humidity: 55,
                        battery: 80,
                        status: Status::Yellow,
                        interval: 60,
                        age: 0,
                        captured_at: Some(OffsetDateTime::now_utc()),
                        radon: None,
                        radiation_rate: None,
                        radiation_total: None,
                        radon_avg_24h: None,
                        radon_avg_7d: None,
                        radon_avg_30d: None,
                    };
                    let guard = store.lock().await;
                    guard.insert_reading("shared-device", &reading).unwrap();
                    drop(guard);
                    tokio::task::yield_now().await;
                }
            }));
        }

        // Wait for all tasks
        for handle in handles {
            handle.await.unwrap();
        }

        // Verify final state
        let guard = store.lock().await;
        let total = guard.count_readings(Some("shared-device")).unwrap();
        assert_eq!(total, 10 + (3 * 5)); // Initial 10 + 3 writers * 5 each = 25
    }

    #[tokio::test]
    async fn test_concurrent_device_upserts() {
        use std::sync::Arc;
        use tokio::sync::Mutex;

        let store = Arc::new(Mutex::new(Store::open_in_memory().unwrap()));

        // Spawn tasks that upsert the same device concurrently
        let mut handles = Vec::new();
        for i in 0..20 {
            let store = Arc::clone(&store);
            handles.push(tokio::spawn(async move {
                let guard = store.lock().await;
                guard
                    .upsert_device("contested-device", Some(&format!("Name-{}", i)))
                    .unwrap();
            }));
        }

        for handle in handles {
            handle.await.unwrap();
        }

        // Device should exist with one of the names
        let guard = store.lock().await;
        let device = guard.get_device("contested-device").unwrap().unwrap();
        assert!(device.name.unwrap().starts_with("Name-"));
    }
}