canon-archive 0.2.2

A CLI tool for organizing large media libraries into a canonical archive
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
//! Source repository — infrastructure layer for fetching sources.
//!
//! This module provides batch fetch functions that return `Source` structs
//! from the database. It is intentionally "dumb" — no domain logic here,
//! just data access.
//!
//! ## Design Principles
//!
//! 1. **Simple SQL**: Queries do data access only, no business logic in WHERE clauses
//! 2. **Batch fetching**: Avoid N+1 queries by fetching in chunks of BATCH_SIZE
//! 3. **Returns domain types**: Functions return `Source` structs, not raw rows
//! 4. **present=1 baked in**: Only fetches present (non-deleted) sources
//!
//! ## Usage
//!
//! ```ignore
//! use canon::source_repo;
//!
//! // Fetch all sources for specific roots
//! let sources = source_repo::batch_fetch_by_roots(conn, &[1, 2, 3])?;
//! ```

use std::collections::HashMap;

use anyhow::Result;
use rusqlite::types::Value;
use rusqlite::OptionalExtension;

use super::db::Connection;
use crate::domain::scan::{FileObservation, Reconciliation};
use crate::domain::source::{NewSource, Source};

/// Batch size for SQL IN clauses. Consistent across all repositories.
pub const BATCH_SIZE: usize = 1000;

/// The columns we SELECT for Source construction.
/// Kept as a constant to ensure consistency across fetch functions.
const SOURCE_COLUMNS: &str = r#"
    s.id,
    s.root_id,
    r.path as root_path,
    s.rel_path,
    s.object_id,
    s.size,
    s.mtime,
    s.excluded,
    o.excluded as object_excluded,
    s.device,
    s.inode,
    s.partial_hash,
    s.basis_rev,
    r.role as root_role,
    r.suspended as root_suspended
"#;

/// The base FROM/JOIN clause for Source queries.
const SOURCE_FROM: &str = r#"
    FROM sources s
    JOIN roots r ON s.root_id = r.id
    LEFT JOIN objects o ON s.object_id = o.id
"#;

/// Construct a Source from a row. Column order must match SOURCE_COLUMNS.
fn source_from_row(row: &rusqlite::Row) -> rusqlite::Result<Source> {
    Ok(Source {
        id: row.get(0)?,
        root_id: row.get(1)?,
        root_path: row.get(2)?,
        rel_path: row.get(3)?,
        object_id: row.get(4)?,
        size: row.get(5)?,
        mtime: row.get(6)?,
        excluded: row.get(7)?,
        object_excluded: row.get(8)?,
        device: row.get(9)?,
        inode: row.get(10)?,
        partial_hash: row.get(11)?,
        basis_rev: row.get(12)?,
        root_role: row.get(13)?,
        root_suspended: row.get(14)?,
    })
}

/// Fetch all present sources for the given root IDs.
///
/// Returns sources in no particular order. Callers should sort if needed.
///
/// This is a simple fetch with no filtering beyond `present = 1`.
/// Domain filtering (scope, exclusion, role) should be done in Rust
/// using the Source predicates.
pub fn batch_fetch_by_roots(conn: &Connection, root_ids: &[i64]) -> Result<Vec<Source>> {
    if root_ids.is_empty() {
        return Ok(Vec::new());
    }

    let mut sources = Vec::new();

    // Process root_ids in batches
    for chunk in root_ids.chunks(BATCH_SIZE) {
        let placeholders: Vec<&str> = chunk.iter().map(|_| "?").collect();
        let sql = format!(
            "SELECT {} {} WHERE s.present = 1 AND s.root_id IN ({})",
            SOURCE_COLUMNS,
            SOURCE_FROM,
            placeholders.join(",")
        );

        let params: Vec<Value> = chunk.iter().map(|&id| Value::from(id)).collect();
        let mut stmt = conn.prepare(&sql)?;
        let rows = stmt.query_map(rusqlite::params_from_iter(params), source_from_row)?;

        for row in rows {
            sources.push(row?);
        }
    }

    Ok(sources)
}

/// Fetch sources by their IDs, returning a HashMap for O(1) lookup.
///
/// This is useful when you have a list of source IDs (e.g., from filter results)
/// and need to fetch the full Source data for each.
///
/// Only present sources are returned. If an ID doesn't exist or the source
/// is not present, it won't appear in the result map.
pub fn batch_fetch_by_ids(conn: &Connection, source_ids: &[i64]) -> Result<HashMap<i64, Source>> {
    if source_ids.is_empty() {
        return Ok(HashMap::new());
    }

    let mut sources = HashMap::with_capacity(source_ids.len());

    // Process source_ids in batches
    for chunk in source_ids.chunks(BATCH_SIZE) {
        let placeholders: Vec<&str> = chunk.iter().map(|_| "?").collect();
        let sql = format!(
            "SELECT {} {} WHERE s.present = 1 AND s.id IN ({})",
            SOURCE_COLUMNS,
            SOURCE_FROM,
            placeholders.join(",")
        );

        let params: Vec<Value> = chunk.iter().map(|&id| Value::from(id)).collect();
        let mut stmt = conn.prepare(&sql)?;
        let rows = stmt.query_map(rusqlite::params_from_iter(params), source_from_row)?;

        for row in rows {
            let source = row?;
            sources.insert(source.id, source);
        }
    }

    Ok(sources)
}

/// Fetch all sources that share the given object IDs, grouped by object_id.
///
/// Used for finding duplicates — given content hashes (via object_id), find all
/// file locations that contain that content.
///
/// # Returns
/// HashMap where key is object_id and value is Vec of all present Sources with
/// that object. Sources include full root_path for path computation via `Source::path()`.
///
/// # Example
/// ```ignore
/// let sources_by_object = fetch_sources_by_object_ids(conn, &object_ids)?;
/// for (object_id, sources) in sources_by_object {
///     // sources contains all files with this content
///     for source in sources {
///         println!("{}", source.path());
///     }
/// }
/// ```
pub fn fetch_sources_by_object_ids(
    conn: &Connection,
    object_ids: &[i64],
) -> Result<HashMap<i64, Vec<Source>>> {
    if object_ids.is_empty() {
        return Ok(HashMap::new());
    }

    let mut result: HashMap<i64, Vec<Source>> = HashMap::new();

    // Process object_ids in batches
    for chunk in object_ids.chunks(BATCH_SIZE) {
        let placeholders: Vec<&str> = chunk.iter().map(|_| "?").collect();
        let sql = format!(
            "SELECT {} {} WHERE s.present = 1 AND s.object_id IN ({})",
            SOURCE_COLUMNS,
            SOURCE_FROM,
            placeholders.join(",")
        );

        let params: Vec<Value> = chunk.iter().map(|&id| Value::from(id)).collect();
        let mut stmt = conn.prepare(&sql)?;
        let rows = stmt.query_map(rusqlite::params_from_iter(params), source_from_row)?;

        for row in rows {
            let source = row?;
            if let Some(object_id) = source.object_id {
                result.entry(object_id).or_default().push(source);
            }
        }
    }

    Ok(result)
}

/// Fetch a single source by root_id and rel_path.
///
/// Returns None if no present source exists at that path.
/// Used during scan reconciliation to find existing source at the observed path.
pub fn fetch_by_path(conn: &Connection, root_id: i64, rel_path: &str) -> Result<Option<Source>> {
    let sql = format!(
        "SELECT {SOURCE_COLUMNS} {SOURCE_FROM} WHERE s.present = 1 AND s.root_id = ? AND s.rel_path = ?",
    );

    let result = conn
        .query_row(&sql, rusqlite::params![root_id, rel_path], source_from_row)
        .optional()?;

    Ok(result)
}

/// Fetch a single source by its ID.
///
/// Returns the complete Source with all joined fields (root_path, root_role, etc.).
/// Returns None if the source doesn't exist or is not present.
///
/// This is useful for operations that have a source_id and need the full
/// Source data (e.g., import processing where source_id comes from worklist).
pub fn fetch_by_id(conn: &Connection, source_id: i64) -> Result<Option<Source>> {
    let sql = format!(
        "SELECT {SOURCE_COLUMNS} {SOURCE_FROM} WHERE s.present = 1 AND s.id = ?",
    );

    let result = conn
        .query_row(&sql, rusqlite::params![source_id], source_from_row)
        .optional()?;

    Ok(result)
}

/// Fetch a source by its device and inode.
///
/// Searches across ALL roots to detect file moves (including cross-root moves).
/// Returns None if no present source exists with matching device+inode.
///
/// # Note
/// This search is global across all roots because files can be moved between roots.
/// The caller should use the returned source's root_id to detect cross-root moves.
pub fn fetch_by_inode(conn: &Connection, device: u64, inode: u64) -> Result<Option<Source>> {
    let sql = format!(
        "SELECT {SOURCE_COLUMNS} {SOURCE_FROM} WHERE s.present = 1 AND s.device = ? AND s.inode = ?",
    );

    let result = conn
        .query_row(
            &sql,
            rusqlite::params![device as i64, inode as i64],
            source_from_row,
        )
        .optional()?;

    Ok(result)
}

/// Check which destination paths are already registered in an archive.
///
/// This is used by apply's preflight check to detect destination conflicts
/// before any file operations begin. In regular mode, any existing paths
/// are an error. In --resume mode, existing paths are classified for skip/transfer.
///
/// # Arguments
/// * `conn` - Database connection
/// * `archive_root_id` - The archive root to check within
/// * `rel_paths` - Relative paths to check (within the archive)
///
/// # Returns
/// Set of rel_paths that exist in the archive with present=1.
/// Paths not in the result set are available for writing.
///
/// # Example
/// ```ignore
/// let existing = batch_check_paths_exist(conn, archive_id, &["2024/a.jpg", "2024/b.jpg"])?;
/// if existing.contains("2024/a.jpg") {
///     // This path is already occupied
/// }
/// ```
pub fn batch_check_paths_exist(
    conn: &Connection,
    archive_root_id: i64,
    rel_paths: &[&str],
) -> Result<std::collections::HashSet<String>> {
    use std::collections::HashSet;

    if rel_paths.is_empty() {
        return Ok(HashSet::new());
    }

    let mut result = HashSet::new();

    // Process rel_paths in batches to avoid SQLite variable limit
    for chunk in rel_paths.chunks(BATCH_SIZE) {
        let placeholders: Vec<&str> = chunk.iter().map(|_| "?").collect();
        let sql = format!(
            "SELECT rel_path FROM sources WHERE root_id = ? AND present = 1 AND rel_path IN ({})",
            placeholders.join(", ")
        );

        // Build params: archive_root_id first, then all rel_paths
        let mut params: Vec<&dyn rusqlite::ToSql> = Vec::with_capacity(chunk.len() + 1);
        params.push(&archive_root_id);
        for path in chunk {
            params.push(path);
        }

        let mut stmt = conn.prepare(&sql)?;
        let rows = stmt.query_map(params.as_slice(), |row| row.get::<_, String>(0))?;

        for row in rows {
            result.insert(row?);
        }
    }

    Ok(result)
}

/// Insert a new source record for a destination file in an archive.
///
/// This function registers a file that has been copied or moved to an archive root.
/// It handles both fresh inserts and updates to stale records.
///
/// # Behavior
///
/// - **Fresh insert**: If no record exists for (root_id, rel_path), creates a new
///   record with basis_rev=0.
/// - **Stale record revival**: If a stale record exists (present=0), updates it
///   with the new metadata, increments basis_rev, and sets present=1. This preserves
///   the row history and correctly reflects that new content now exists at this path.
/// - **Active record conflict**: If an active record exists (present=1), returns an
///   error. The caller's pre-flight check should have prevented this.
///
/// # Returns
///
/// The complete Source record as it exists in the database after the operation,
/// including joined fields (root_path, root_role, root_suspended, object_excluded).
/// This is fetched via SELECT after the write to ensure accuracy.
///
/// # Caller Responsibilities
///
/// - Ensure the file has been successfully written to disk before calling
/// - Manage transaction boundaries (this function does not BEGIN/COMMIT)
/// - Run pre-flight checks to detect active record conflicts before file operations
///
/// # Example
///
/// ```ignore
/// let new_source = NewSource {
///     root_id: archive_root_id,
///     rel_path: "2024/photo.jpg".to_string(),
///     size: 1024,
///     mtime: 1704067200,
///     partial_hash: "abc123".to_string(),
///     object_id: Some(42),
///     device: Some(65024),
///     inode: Some(12345),
/// };
///
/// let created = repo::source::insert_destination(conn, &new_source)?;
/// println!("Created source {} at {}", created.id, created.path());
/// ```
pub fn insert_destination(conn: &Connection, new: &NewSource) -> Result<Source> {
    use std::time::{SystemTime, UNIX_EPOCH};

    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .expect("Time went backwards")
        .as_secs() as i64;

    // First try to update an existing stale record (present=0).
    // This preserves the row and increments basis_rev to reflect new content at this path.
    let updated = conn.execute(
        "UPDATE sources SET
            device = COALESCE(?, device),
            inode = COALESCE(?, inode),
            size = ?,
            mtime = ?,
            partial_hash = ?,
            object_id = ?,
            basis_rev = basis_rev + 1,
            scanned_at = ?,
            last_seen_at = ?,
            present = 1,
            excluded = 0
         WHERE root_id = ? AND rel_path = ? AND present = 0",
        rusqlite::params![
            new.device,
            new.inode,
            new.size,
            new.mtime,
            new.partial_hash,
            new.object_id,
            now,
            now,
            new.root_id,
            new.rel_path,
        ],
    )?;

    if updated == 0 {
        // No stale record exists. Insert new record.
        // Use COALESCE for device/inode to handle platforms without these values.
        conn.execute(
            "INSERT INTO sources (
                root_id, rel_path, device, inode, size, mtime, partial_hash,
                object_id, basis_rev, scanned_at, last_seen_at, present, excluded
             ) VALUES (?, ?, COALESCE(?, 0), COALESCE(?, 0), ?, ?, ?, ?, 0, ?, ?, 1, 0)",
            rusqlite::params![
                new.root_id,
                new.rel_path,
                new.device,
                new.inode,
                new.size,
                new.mtime,
                new.partial_hash,
                new.object_id,
                now,
                now,
            ],
        )?;
    }

    // Fetch the complete Source record with all joined fields.
    // This ensures the returned Source accurately reflects database state.
    fetch_by_path(conn, new.root_id, &new.rel_path)?.ok_or_else(|| {
        anyhow::anyhow!(
            "Failed to fetch source after insert: root_id={}, rel_path={}",
            new.root_id,
            new.rel_path
        )
    })
}

/// Apply a reconciliation outcome to the database.
///
/// Translates the domain `Reconciliation` into the appropriate SQL operation.
/// This function does NOT manage transactions — the caller should wrap the call
/// in a transaction if atomicity with other operations is needed.
///
/// # Behavior by Reconciliation variant
///
/// - **New**: INSERT source with basis_rev=0, scanned_at=now, present=1
/// - **Unchanged**: UPDATE last_seen_at=now only
/// - **Modified**: UPDATE size, mtime, partial_hash, device, inode, basis_rev+1, last_seen_at=now
/// - **Moved**: UPDATE root_id, rel_path, device, inode, size, mtime, last_seen_at=now
/// - **Disconnected**: No database operation; returns the existing Source unchanged
///
/// # Returns
///
/// The complete Source record after the operation (via SELECT).
/// This ensures the returned Source accurately reflects database state,
/// including all joined fields (root_path, root_role, object_excluded).
///
/// # Caller Responsibilities
///
/// - Ensure `observation.partial_hash` is set for New and Modified reconciliations
/// - Manage transaction boundaries
/// - Handle Disconnected appropriately (log warning, track in stats)
pub fn apply_reconciliation(
    conn: &Connection,
    observation: &FileObservation,
    reconciliation: &Reconciliation,
    now: i64,
) -> Result<Source> {
    match reconciliation {
        Reconciliation::New => {
            // INSERT new source with basis_rev=0, or revive stale record at same path.
            //
            // Two cases lead here:
            // 1. Truly new file: no record exists at this path
            // 2. Replaced file: old file was deleted/marked-missing, new file created at same path
            //
            // We use the same two-step pattern as insert_destination():
            // - First try UPDATE WHERE present=0 (revive stale record)
            // - If no rows updated, INSERT new record
            let partial_hash = observation
                .partial_hash
                .as_ref()
                .ok_or_else(|| anyhow::anyhow!("partial_hash required for New reconciliation"))?;

            // Step 1: Try to update any existing record at this path (stale or replaced)
            // - Stale (present=0): file reappeared at previously-used path
            // - Replaced (present=1, different inode): old file deleted, new file at same path
            let updated = conn.execute(
                "UPDATE sources SET
                    device = ?, inode = ?, size = ?, mtime = ?, partial_hash = ?,
                    basis_rev = 0, scanned_at = ?, last_seen_at = ?,
                    present = 1, excluded = 0, object_id = NULL
                 WHERE root_id = ? AND rel_path = ?",
                rusqlite::params![
                    observation.device as i64,
                    observation.inode as i64,
                    observation.size,
                    observation.mtime,
                    partial_hash,
                    now,
                    now,
                    observation.root_id,
                    observation.rel_path,
                ],
            )?;

            if updated == 0 {
                // Step 2: No stale record exists, insert new
                conn.execute(
                    "INSERT INTO sources (
                        root_id, rel_path, device, inode, size, mtime, partial_hash,
                        basis_rev, scanned_at, last_seen_at, present, excluded
                     ) VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?, ?, 1, 0)",
                    rusqlite::params![
                        observation.root_id,
                        observation.rel_path,
                        observation.device as i64,
                        observation.inode as i64,
                        observation.size,
                        observation.mtime,
                        partial_hash,
                        now,
                        now,
                    ],
                )?;
            }

            fetch_by_path(conn, observation.root_id, &observation.rel_path)?
                .ok_or_else(|| anyhow::anyhow!("Failed to fetch source after insert"))
        }

        Reconciliation::Unchanged { source_id } => {
            // UPDATE last_seen_at and device/inode metadata
            // Device/inode may change legitimately (e.g., NAS remount, drive replacement)
            // Even though content is unchanged, we update current location metadata
            conn.execute(
                "UPDATE sources SET device = ?, inode = ?, last_seen_at = ? WHERE id = ?",
                rusqlite::params![
                    observation.device as i64,
                    observation.inode as i64,
                    now,
                    source_id
                ],
            )?;

            fetch_by_id(conn, *source_id)?
                .ok_or_else(|| anyhow::anyhow!("Failed to fetch source after update"))
        }

        Reconciliation::Modified { source_id, .. } => {
            // UPDATE with new metadata, increment basis_rev
            let partial_hash = observation.partial_hash.as_ref().ok_or_else(|| {
                anyhow::anyhow!("partial_hash required for Modified reconciliation")
            })?;

            conn.execute(
                "UPDATE sources SET
                    device = ?, inode = ?, size = ?, mtime = ?,
                    partial_hash = ?, basis_rev = basis_rev + 1,
                    last_seen_at = ?, present = 1
                 WHERE id = ?",
                rusqlite::params![
                    observation.device as i64,
                    observation.inode as i64,
                    observation.size,
                    observation.mtime,
                    partial_hash,
                    now,
                    source_id,
                ],
            )?;

            fetch_by_id(conn, *source_id)?
                .ok_or_else(|| anyhow::anyhow!("Failed to fetch source after update"))
        }

        Reconciliation::Moved { source_id, .. } => {
            // UPDATE path and location metadata
            conn.execute(
                "UPDATE sources SET
                    root_id = ?, rel_path = ?,
                    device = ?, inode = ?, size = ?, mtime = ?,
                    last_seen_at = ?, present = 1
                 WHERE id = ?",
                rusqlite::params![
                    observation.root_id,
                    observation.rel_path,
                    observation.device as i64,
                    observation.inode as i64,
                    observation.size,
                    observation.mtime,
                    now,
                    source_id,
                ],
            )?;

            fetch_by_id(conn, *source_id)?
                .ok_or_else(|| anyhow::anyhow!("Failed to fetch source after update"))
        }
    }
}

/// Mark sources as no longer present (missing from filesystem).
///
/// Sets `present=0` for all specified source IDs. This does NOT delete records —
/// the history is preserved for tracking and potential revival if the file reappears.
///
/// # Arguments
///
/// - `source_ids`: IDs of sources to mark as missing
/// - `now`: Timestamp to record as last_seen_at
///
/// # Returns
///
/// Count of sources that were marked as missing.
///
/// # Note
///
/// Sources already marked as not present (present=0) are not counted in the return value.
/// This function handles empty input gracefully (returns 0).
pub fn mark_missing(conn: &Connection, source_ids: &[i64], now: i64) -> Result<u64> {
    if source_ids.is_empty() {
        return Ok(0);
    }

    let mut total_updated = 0u64;

    for chunk in source_ids.chunks(BATCH_SIZE) {
        let placeholders: Vec<&str> = chunk.iter().map(|_| "?").collect();
        let sql = format!(
            "UPDATE sources SET present = 0, last_seen_at = ? WHERE present = 1 AND id IN ({})",
            placeholders.join(",")
        );

        // Build params: now first, then all the IDs
        let mut params: Vec<rusqlite::types::Value> = Vec::with_capacity(chunk.len() + 1);
        params.push(rusqlite::types::Value::from(now));
        for &id in chunk {
            params.push(rusqlite::types::Value::from(id));
        }

        let updated = conn.execute(&sql, rusqlite::params_from_iter(params))?;
        total_updated += updated as u64;
    }

    Ok(total_updated)
}

/// Fetch source IDs for a given root (for missing detection).
///
/// Returns the set of present source IDs for the specified root.
/// Used at the start of a scan to track which sources should be seen.
///
/// # Arguments
/// - `conn`: Database connection
/// - `root_id`: The root to fetch sources for
/// - `scan_prefix`: Optional path prefix to filter sources (e.g., "photos/" only returns
///   sources whose rel_path starts with "photos/")
pub fn fetch_source_ids_for_root(
    conn: &Connection,
    root_id: i64,
    scan_prefix: Option<&str>,
) -> Result<Vec<i64>> {
    let ids: Vec<i64> = match scan_prefix {
        Some(prefix) => {
            let pattern = format!("{prefix}%");
            conn.prepare(
                "SELECT id FROM sources WHERE root_id = ? AND present = 1 AND rel_path LIKE ?",
            )?
            .query_map(rusqlite::params![root_id, pattern], |row| row.get(0))?
            .collect::<Result<Vec<_>, _>>()?
        }
        None => conn
            .prepare("SELECT id FROM sources WHERE root_id = ? AND present = 1")?
            .query_map(rusqlite::params![root_id], |row| row.get(0))?
            .collect::<Result<Vec<_>, _>>()?,
    };

    Ok(ids)
}

/// Set the exclusion flag for a single source.
///
/// # Behavior
/// - Updates `excluded` column to the specified value
/// - No error if source doesn't exist (0 rows affected)
/// - Does NOT affect object-level exclusion
///
/// # Returns
/// Ok(()) on success. To verify the source existed, use batch variant which returns count.
pub fn set_excluded(conn: &Connection, source_id: i64, excluded: bool) -> Result<()> {
    conn.execute(
        "UPDATE sources SET excluded = ? WHERE id = ?",
        rusqlite::params![excluded as i64, source_id],
    )?;
    Ok(())
}

/// Set the exclusion flag for multiple sources.
///
/// # Behavior
/// - Updates `excluded` column for all specified sources
/// - Handles large inputs via chunking (BATCH_SIZE = 1000)
/// - Sources that don't exist are silently skipped
///
/// # Returns
/// Count of rows actually updated (may be less than input if some sources don't exist).
#[allow(dead_code)] // Part of repo API, may be used in future
pub fn batch_set_excluded(conn: &Connection, source_ids: &[i64], excluded: bool) -> Result<u64> {
    if source_ids.is_empty() {
        return Ok(0);
    }

    let mut total_updated = 0u64;

    for chunk in source_ids.chunks(BATCH_SIZE) {
        let placeholders: Vec<&str> = chunk.iter().map(|_| "?").collect();
        let sql = format!(
            "UPDATE sources SET excluded = ? WHERE id IN ({})",
            placeholders.join(",")
        );

        // Build params: excluded flag first, then all the IDs
        let mut params: Vec<rusqlite::types::Value> = Vec::with_capacity(chunk.len() + 1);
        params.push(rusqlite::types::Value::from(excluded as i64));
        for &id in chunk {
            params.push(rusqlite::types::Value::from(id));
        }

        let updated = conn.execute(&sql, rusqlite::params_from_iter(params))?;
        total_updated += updated as u64;
    }

    Ok(total_updated)
}

/// Count sources in a root by hash status.
///
/// Returns (total, unhashed) where:
/// - `total` is the count of present sources in the root
/// - `unhashed` is the count of sources without an object_id (no content hash)
///
/// Used to verify archive hash coverage before apply operations.
pub fn count_unhashed_for_root(conn: &Connection, root_id: i64) -> Result<(i64, i64)> {
    let (total, unhashed): (i64, i64) = conn.query_row(
        "SELECT COUNT(*), COALESCE(SUM(CASE WHEN object_id IS NULL THEN 1 ELSE 0 END), 0)
         FROM sources WHERE root_id = ? AND present = 1",
        [root_id],
        |row| Ok((row.get(0)?, row.get(1)?)),
    )?;
    Ok((total, unhashed))
}

/// Update a source's location (root and path) after a rename/move operation.
///
/// Used when a source file is relocated to an archive. Updates the root_id,
/// rel_path, and timestamps to reflect the new location.
///
/// # Arguments
/// * `conn` - Database connection
/// * `source_id` - ID of the source to update
/// * `new_root_id` - The new root (typically the archive root)
/// * `new_rel_path` - The new relative path within the root
/// * `now` - Timestamp to record
pub fn update_location(
    conn: &Connection,
    source_id: i64,
    new_root_id: i64,
    new_rel_path: &str,
    now: i64,
) -> Result<()> {
    conn.execute(
        "UPDATE sources SET root_id = ?, rel_path = ?, scanned_at = ?, last_seen_at = ?
         WHERE id = ?",
        rusqlite::params![new_root_id, new_rel_path, now, now, source_id],
    )?;
    Ok(())
}

/// Fetch source IDs and device info for sources matching a path prefix.
///
/// Used by scan to detect disconnected sources (sources on a different device
/// than the current scan). Returns `(source_id, device)` pairs for mount
/// protection logic.
///
/// # Arguments
/// * `conn` - Database connection
/// * `root_id` - The root to search within
/// * `rel_prefix` - Relative path prefix (empty string matches all)
///
/// # Returns
/// Vector of (source_id, device) tuples for present sources matching the prefix.
pub fn fetch_device_info_by_prefix(
    conn: &Connection,
    root_id: i64,
    rel_prefix: &str,
) -> Result<Vec<(i64, Option<i64>)>> {
    // Build LIKE pattern: empty prefix matches all, otherwise "prefix/%"
    let prefix_pattern = if rel_prefix.is_empty() {
        "%".to_string()
    } else {
        format!("{rel_prefix}/%")
    };

    let mut stmt = conn.prepare(
        "SELECT id, device FROM sources WHERE root_id = ? AND rel_path LIKE ? AND present = 1",
    )?;
    let rows = stmt.query_map(rusqlite::params![root_id, prefix_pattern], |row| {
        Ok((row.get(0)?, row.get(1)?))
    })?;

    let mut results = Vec::new();
    for row in rows {
        results.push(row?);
    }
    Ok(results)
}

/// Set the object_id for a source after hashing.
///
/// Links a source to its content object after the file has been hashed.
pub fn set_object_id(conn: &Connection, source_id: i64, object_id: i64) -> Result<()> {
    conn.execute(
        "UPDATE sources SET object_id = ? WHERE id = ?",
        rusqlite::params![object_id, source_id],
    )?;
    Ok(())
}

/// Insert a source for testing purposes.
///
/// This function is only available in test builds. It provides a simple way
/// to set up test data with specific device/inode values for move detection tests.
#[cfg(test)]
pub fn insert_test_source(
    conn: &Connection,
    root_id: i64,
    rel_path: &str,
    device: i64,
    inode: i64,
    size: i64,
    mtime: i64,
) -> i64 {
    conn.execute(
        "INSERT INTO sources (root_id, rel_path, device, inode, size, mtime, partial_hash, scanned_at, last_seen_at)
         VALUES (?, ?, ?, ?, ?, ?, 'testhash', 0, 0)",
        rusqlite::params![root_id, rel_path, device, inode, size, mtime],
    )
    .unwrap();
    conn.last_insert_rowid()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::repo::open_in_memory_for_test;
    use rusqlite::Connection as RusqliteConnection;

    /// Create an in-memory database with the full schema.
    fn setup_test_db() -> RusqliteConnection {
        open_in_memory_for_test()
    }

    /// Insert a test object and return its ID
    fn insert_object(conn: &RusqliteConnection, hash: &str, excluded: bool) -> i64 {
        conn.execute(
            "INSERT INTO objects (hash_type, hash_value, excluded) VALUES ('sha256', ?, ?)",
            rusqlite::params![hash, excluded as i64],
        )
        .unwrap();
        conn.last_insert_rowid()
    }

    /// Insert a test source and return its ID
    fn insert_source(
        conn: &RusqliteConnection,
        root_id: i64,
        rel_path: &str,
        object_id: Option<i64>,
        present: bool,
        excluded: bool,
    ) -> i64 {
        conn.execute(
            "INSERT INTO sources (root_id, rel_path, object_id, device, inode, size, mtime, partial_hash, scanned_at, last_seen_at, present, excluded)
             VALUES (?, ?, ?, 0, 0, 1000, 1704067200, 'hash', 0, 0, ?, ?)",
            rusqlite::params![root_id, rel_path, object_id, present as i64, excluded as i64],
        )
        .unwrap();
        conn.last_insert_rowid()
    }

    // =========================================================================
    // batch_fetch_by_roots tests
    // =========================================================================

    #[test]
    fn batch_fetch_by_roots_empty_ids() {
        let conn = setup_test_db();
        let result = batch_fetch_by_roots(&conn, &[]).unwrap();
        assert!(result.is_empty());
    }

    #[test]
    fn batch_fetch_by_roots_no_matching_roots() {
        let conn = setup_test_db();
        // Query for non-existent root IDs
        let result = batch_fetch_by_roots(&conn, &[999, 1000]).unwrap();
        assert!(result.is_empty());
    }

    #[test]
    fn batch_fetch_by_roots_single_root() {
        let conn = setup_test_db();

        let root_id = crate::repo::insert_test_root(&conn, "/photos", "source", false);
        insert_source(&conn, root_id, "a.jpg", None, true, false);
        insert_source(&conn, root_id, "b.jpg", None, true, false);

        let sources = batch_fetch_by_roots(&conn, &[root_id]).unwrap();
        assert_eq!(sources.len(), 2);

        // Verify source data is populated correctly
        let source = sources.iter().find(|s| s.rel_path == "a.jpg").unwrap();
        assert_eq!(source.root_path, "/photos");
        assert_eq!(source.root_role, "source");
        assert!(!source.root_suspended);
    }

    #[test]
    fn batch_fetch_by_roots_multiple_roots() {
        let conn = setup_test_db();

        let root1 = crate::repo::insert_test_root(&conn, "/photos", "source", false);
        let root2 = crate::repo::insert_test_root(&conn, "/archive", "archive", false);

        insert_source(&conn, root1, "photo.jpg", None, true, false);
        insert_source(&conn, root2, "backup.jpg", None, true, false);

        let sources = batch_fetch_by_roots(&conn, &[root1, root2]).unwrap();
        assert_eq!(sources.len(), 2);

        // Verify roles are correct
        let photo = sources.iter().find(|s| s.rel_path == "photo.jpg").unwrap();
        assert_eq!(photo.root_role, "source");

        let backup = sources.iter().find(|s| s.rel_path == "backup.jpg").unwrap();
        assert_eq!(backup.root_role, "archive");
    }

    #[test]
    fn batch_fetch_by_roots_excludes_non_present() {
        let conn = setup_test_db();

        let root_id = crate::repo::insert_test_root(&conn, "/photos", "source", false);
        insert_source(&conn, root_id, "present.jpg", None, true, false);
        insert_source(&conn, root_id, "deleted.jpg", None, false, false); // present=false

        let sources = batch_fetch_by_roots(&conn, &[root_id]).unwrap();
        assert_eq!(sources.len(), 1);
        assert_eq!(sources[0].rel_path, "present.jpg");
    }

    #[test]
    fn batch_fetch_by_roots_includes_excluded_sources() {
        // Repository layer fetches ALL present sources, including excluded ones.
        // Filtering by exclusion is done in the domain layer.
        let conn = setup_test_db();

        let root_id = crate::repo::insert_test_root(&conn, "/photos", "source", false);
        insert_source(&conn, root_id, "normal.jpg", None, true, false);
        insert_source(&conn, root_id, "excluded.jpg", None, true, true); // excluded=true

        let sources = batch_fetch_by_roots(&conn, &[root_id]).unwrap();
        assert_eq!(sources.len(), 2);

        let excluded = sources
            .iter()
            .find(|s| s.rel_path == "excluded.jpg")
            .unwrap();
        assert!(excluded.excluded);
    }

    #[test]
    fn batch_fetch_by_roots_includes_object_excluded() {
        let conn = setup_test_db();

        let root_id = crate::repo::insert_test_root(&conn, "/photos", "source", false);
        let obj_id = insert_object(&conn, "abc123", true); // object excluded
        insert_source(&conn, root_id, "file.jpg", Some(obj_id), true, false);

        let sources = batch_fetch_by_roots(&conn, &[root_id]).unwrap();
        assert_eq!(sources.len(), 1);

        let source = &sources[0];
        assert!(!source.excluded); // source not excluded
        assert_eq!(source.object_excluded, Some(true)); // but object is
        assert!(source.is_excluded()); // domain predicate catches both
    }

    #[test]
    fn batch_fetch_by_roots_suspended_root() {
        let conn = setup_test_db();

        let root_id = crate::repo::insert_test_root(&conn, "/photos", "source", true); // suspended
        insert_source(&conn, root_id, "file.jpg", None, true, false);

        let sources = batch_fetch_by_roots(&conn, &[root_id]).unwrap();
        assert_eq!(sources.len(), 1);
        assert!(sources[0].root_suspended);
        assert!(!sources[0].is_active()); // domain predicate
    }

    // =========================================================================
    // batch_fetch_by_ids tests
    // =========================================================================

    #[test]
    fn batch_fetch_by_ids_empty_ids() {
        let conn = setup_test_db();
        let result = batch_fetch_by_ids(&conn, &[]).unwrap();
        assert!(result.is_empty());
    }

    #[test]
    fn batch_fetch_by_ids_no_matching_ids() {
        let conn = setup_test_db();
        let result = batch_fetch_by_ids(&conn, &[999, 1000]).unwrap();
        assert!(result.is_empty());
    }

    #[test]
    fn batch_fetch_by_ids_returns_hashmap() {
        let conn = setup_test_db();

        let root_id = crate::repo::insert_test_root(&conn, "/photos", "source", false);
        let id1 = insert_source(&conn, root_id, "a.jpg", None, true, false);
        let id2 = insert_source(&conn, root_id, "b.jpg", None, true, false);

        let sources = batch_fetch_by_ids(&conn, &[id1, id2]).unwrap();
        assert_eq!(sources.len(), 2);

        // Verify O(1) lookup works
        assert_eq!(sources.get(&id1).unwrap().rel_path, "a.jpg");
        assert_eq!(sources.get(&id2).unwrap().rel_path, "b.jpg");
    }

    #[test]
    fn batch_fetch_by_ids_excludes_non_present() {
        let conn = setup_test_db();

        let root_id = crate::repo::insert_test_root(&conn, "/photos", "source", false);
        let present_id = insert_source(&conn, root_id, "present.jpg", None, true, false);
        let deleted_id = insert_source(&conn, root_id, "deleted.jpg", None, false, false);

        let sources = batch_fetch_by_ids(&conn, &[present_id, deleted_id]).unwrap();
        assert_eq!(sources.len(), 1);
        assert!(sources.contains_key(&present_id));
        assert!(!sources.contains_key(&deleted_id));
    }

    #[test]
    fn batch_fetch_by_ids_partial_match() {
        let conn = setup_test_db();

        let root_id = crate::repo::insert_test_root(&conn, "/photos", "source", false);
        let id1 = insert_source(&conn, root_id, "exists.jpg", None, true, false);

        // Query for mix of existing and non-existing IDs
        let sources = batch_fetch_by_ids(&conn, &[id1, 999, 1000]).unwrap();
        assert_eq!(sources.len(), 1);
        assert!(sources.contains_key(&id1));
    }

    // =========================================================================
    // fetch_by_id tests
    // =========================================================================

    #[test]
    fn fetch_by_id_returns_source() {
        let conn = setup_test_db();

        let root_id = crate::repo::insert_test_root(&conn, "/photos", "source", false);
        let obj_id = insert_object(&conn, "abc123", false);
        let source_id = insert_source(&conn, root_id, "photo.jpg", Some(obj_id), true, false);

        let result = fetch_by_id(&conn, source_id).unwrap();

        assert!(result.is_some());
        let source = result.unwrap();
        assert_eq!(source.id, source_id);
        assert_eq!(source.root_id, root_id);
        assert_eq!(source.root_path, "/photos");
        assert_eq!(source.rel_path, "photo.jpg");
        assert_eq!(source.object_id, Some(obj_id));
        assert_eq!(source.root_role, "source");
    }

    #[test]
    fn fetch_by_id_not_found() {
        let conn = setup_test_db();

        let result = fetch_by_id(&conn, 99999).unwrap();

        assert!(result.is_none());
    }

    #[test]
    fn fetch_by_id_excludes_non_present() {
        let conn = setup_test_db();

        let root_id = crate::repo::insert_test_root(&conn, "/photos", "source", false);
        let source_id = insert_source(&conn, root_id, "deleted.jpg", None, false, false); // present=false

        let result = fetch_by_id(&conn, source_id).unwrap();

        assert!(result.is_none());
    }

    #[test]
    fn fetch_by_id_includes_excluded_source() {
        let conn = setup_test_db();

        let root_id = crate::repo::insert_test_root(&conn, "/photos", "source", false);
        let source_id = insert_source(&conn, root_id, "excluded.jpg", None, true, true); // excluded=true

        let result = fetch_by_id(&conn, source_id).unwrap();

        assert!(result.is_some());
        let source = result.unwrap();
        assert!(source.excluded);
    }

    // =========================================================================
    // fetch_sources_by_object_ids tests
    // =========================================================================

    #[test]
    fn fetch_sources_by_object_ids_empty_input() {
        let conn = setup_test_db();
        let result = fetch_sources_by_object_ids(&conn, &[]).unwrap();
        assert!(result.is_empty());
    }

    #[test]
    fn fetch_sources_by_object_ids_returns_grouped() {
        let conn = setup_test_db();

        let root1 = crate::repo::insert_test_root(&conn, "/source", "source", false);
        let root2 = crate::repo::insert_test_root(&conn, "/archive", "archive", false);

        // Two objects (different content)
        let obj1 = insert_object(&conn, "content_hash_1", false);
        let obj2 = insert_object(&conn, "content_hash_2", false);

        // obj1 has 2 sources (duplicates)
        let _src1a = insert_source(&conn, root1, "photo.jpg", Some(obj1), true, false);
        let _src1b = insert_source(&conn, root2, "photo.jpg", Some(obj1), true, false);

        // obj2 has 1 source
        let _src2 = insert_source(&conn, root1, "unique.jpg", Some(obj2), true, false);

        let result = fetch_sources_by_object_ids(&conn, &[obj1, obj2]).unwrap();

        // Should have 2 keys
        assert_eq!(result.len(), 2);

        // obj1 should have 2 sources
        assert_eq!(result.get(&obj1).map(|v| v.len()), Some(2));

        // obj2 should have 1 source
        assert_eq!(result.get(&obj2).map(|v| v.len()), Some(1));
    }

    #[test]
    fn fetch_sources_by_object_ids_includes_root_path() {
        let conn = setup_test_db();

        let root_id = crate::repo::insert_test_root(&conn, "/my/archive", "archive", false);
        let obj = insert_object(&conn, "test_hash", false);
        let _src = insert_source(&conn, root_id, "subdir/file.txt", Some(obj), true, false);

        let result = fetch_sources_by_object_ids(&conn, &[obj]).unwrap();
        let sources = result.get(&obj).unwrap();

        assert_eq!(sources.len(), 1);
        assert_eq!(sources[0].root_path, "/my/archive");
        assert_eq!(sources[0].rel_path, "subdir/file.txt");
        // Verify Source::path() works correctly
        assert_eq!(sources[0].path(), "/my/archive/subdir/file.txt");
    }

    #[test]
    fn fetch_sources_by_object_ids_excludes_non_present() {
        let conn = setup_test_db();

        let root_id = crate::repo::insert_test_root(&conn, "/source", "source", false);
        let obj = insert_object(&conn, "test_hash", false);

        // One present, one deleted
        let _present = insert_source(&conn, root_id, "present.jpg", Some(obj), true, false);
        let _deleted = insert_source(&conn, root_id, "deleted.jpg", Some(obj), false, false);

        let result = fetch_sources_by_object_ids(&conn, &[obj]).unwrap();
        let sources = result.get(&obj).unwrap();

        // Only the present source should be returned
        assert_eq!(sources.len(), 1);
        assert_eq!(sources[0].rel_path, "present.jpg");
    }

    #[test]
    fn fetch_sources_by_object_ids_handles_large_batch() {
        let conn = setup_test_db();

        let root_id = crate::repo::insert_test_root(&conn, "/source", "source", false);

        // Create more than BATCH_SIZE objects (1000+)
        let mut object_ids = Vec::new();
        for i in 0..1050 {
            let obj = insert_object(&conn, &format!("hash_{i}"), false);
            insert_source(
                &conn,
                root_id,
                &format!("file_{i}.jpg"),
                Some(obj),
                true,
                false,
            );
            object_ids.push(obj);
        }

        let result = fetch_sources_by_object_ids(&conn, &object_ids).unwrap();

        // Should have all 1050 objects
        assert_eq!(result.len(), 1050);

        // Verify samples from different batch chunks
        assert!(result.contains_key(&object_ids[0]));
        assert!(result.contains_key(&object_ids[500]));
        assert!(result.contains_key(&object_ids[1049]));
    }

    // =========================================================================
    // insert_destination tests
    // =========================================================================

    #[test]
    fn insert_destination_fresh_insert() {
        let conn = setup_test_db();

        let root_id = crate::repo::insert_test_root(&conn, "/archive", "archive", false);
        let obj_id = insert_object(&conn, "abc123hash", false);

        let new = NewSource {
            root_id,
            rel_path: "2024/photo.jpg".to_string(),
            size: 1024,
            mtime: 1704067200,
            partial_hash: "partial123".to_string(),
            object_id: Some(obj_id),
            device: Some(65024),
            inode: Some(12345),
        };

        let source = insert_destination(&conn, &new).unwrap();

        // Verify returned Source has correct values
        assert_eq!(source.root_id, root_id);
        assert_eq!(source.rel_path, "2024/photo.jpg");
        assert_eq!(source.size, 1024);
        assert_eq!(source.mtime, 1704067200);
        assert_eq!(source.partial_hash, "partial123");
        assert_eq!(source.object_id, Some(obj_id));
        assert_eq!(source.device, 65024);
        assert_eq!(source.inode, 12345);
        // Fresh insert should have basis_rev = 0
        assert_eq!(source.basis_rev, 0);
        // Should not be excluded
        assert!(!source.excluded);
    }

    #[test]
    fn insert_destination_stale_record_update() {
        let conn = setup_test_db();

        let root_id = crate::repo::insert_test_root(&conn, "/archive", "archive", false);
        let obj_id = insert_object(&conn, "abc123hash", false);

        // Insert a stale record (present=0) with basis_rev=5
        conn.execute(
            "INSERT INTO sources (root_id, rel_path, object_id, size, mtime, partial_hash,
             basis_rev, scanned_at, last_seen_at, present, excluded, device, inode)
             VALUES (?, ?, ?, 500, 1700000000, 'oldhash', 5, 0, 0, 0, 1, 100, 200)",
            rusqlite::params![root_id, "revived.jpg", obj_id],
        )
        .unwrap();

        let new = NewSource {
            root_id,
            rel_path: "revived.jpg".to_string(),
            size: 2048,
            mtime: 1704067200,
            partial_hash: "newhash".to_string(),
            object_id: Some(obj_id),
            device: Some(65024),
            inode: Some(99999),
        };

        let source = insert_destination(&conn, &new).unwrap();

        // Verify stale record was updated, not inserted
        assert_eq!(source.rel_path, "revived.jpg");
        assert_eq!(source.size, 2048);
        assert_eq!(source.mtime, 1704067200);
        assert_eq!(source.partial_hash, "newhash");
        // basis_rev should be incremented from 5 to 6
        assert_eq!(source.basis_rev, 6);
        // device/inode should be updated
        assert_eq!(source.device, 65024);
        assert_eq!(source.inode, 99999);
        // excluded should be reset to false
        assert!(!source.excluded);

        // Verify only one record exists
        let count: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM sources WHERE root_id = ? AND rel_path = ?",
                rusqlite::params![root_id, "revived.jpg"],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(count, 1);
    }

    #[test]
    fn insert_destination_null_device_inode() {
        let conn = setup_test_db();

        let root_id = crate::repo::insert_test_root(&conn, "/archive", "archive", false);
        let obj_id = insert_object(&conn, "abc123hash", false);

        // Simulate non-Unix platform where device/inode are not available
        let new = NewSource {
            root_id,
            rel_path: "nonunix.jpg".to_string(),
            size: 1024,
            mtime: 1704067200,
            partial_hash: "partial123".to_string(),
            object_id: Some(obj_id),
            device: None, // Not available
            inode: None,  // Not available
        };

        let source = insert_destination(&conn, &new).unwrap();

        // Should succeed with device/inode defaulting to 0
        assert_eq!(source.rel_path, "nonunix.jpg");
        assert_eq!(source.device, 0);
        assert_eq!(source.inode, 0);
        assert_eq!(source.size, 1024);
    }

    #[test]
    fn insert_destination_already_present_fails() {
        let conn = setup_test_db();

        let root_id = crate::repo::insert_test_root(&conn, "/archive", "archive", false);
        let obj_id = insert_object(&conn, "abc123hash", false);

        // Insert an active record (present=1)
        insert_source(&conn, root_id, "existing.jpg", Some(obj_id), true, false);

        let new = NewSource {
            root_id,
            rel_path: "existing.jpg".to_string(),
            size: 2048,
            mtime: 1704067200,
            partial_hash: "newhash".to_string(),
            object_id: Some(obj_id),
            device: Some(65024),
            inode: Some(12345),
        };

        // Should fail due to UNIQUE constraint on (root_id, rel_path)
        let result = insert_destination(&conn, &new);
        assert!(result.is_err());

        // Verify the error mentions constraint violation
        let err_msg = result.unwrap_err().to_string();
        assert!(err_msg.contains("UNIQUE") || err_msg.contains("constraint"));
    }

    #[test]
    fn insert_destination_returns_complete_source() {
        // Verify the returned Source has all joined fields populated
        let conn = setup_test_db();

        let root_id = crate::repo::insert_test_root(&conn, "/archive", "archive", false);
        let obj_id = insert_object(&conn, "abc123hash", true); // object is excluded

        let new = NewSource {
            root_id,
            rel_path: "complete.jpg".to_string(),
            size: 1024,
            mtime: 1704067200,
            partial_hash: "partial123".to_string(),
            object_id: Some(obj_id),
            device: Some(65024),
            inode: Some(12345),
        };

        let source = insert_destination(&conn, &new).unwrap();

        // Verify joined fields from roots table
        assert_eq!(source.root_path, "/archive");
        assert_eq!(source.root_role, "archive");
        assert!(!source.root_suspended);

        // Verify joined fields from objects table
        assert_eq!(source.object_id, Some(obj_id));
        assert_eq!(source.object_excluded, Some(true));

        // Verify domain predicate works with joined data
        assert!(source.is_excluded()); // object is excluded
        assert!(source.is_active()); // root is not suspended
        assert!(source.is_from_role("archive"));

        // Verify path() works
        assert_eq!(source.path(), "/archive/complete.jpg");
    }

    // =========================================================================
    // fetch_by_path tests
    // =========================================================================

    #[test]
    fn fetch_by_path_exists() {
        let conn = setup_test_db();

        let root_id = crate::repo::insert_test_root(&conn, "/photos", "source", false);
        insert_source(&conn, root_id, "found.jpg", None, true, false);

        let result = fetch_by_path(&conn, root_id, "found.jpg").unwrap();
        assert!(result.is_some());
        assert_eq!(result.unwrap().rel_path, "found.jpg");
    }

    #[test]
    fn fetch_by_path_not_present() {
        let conn = setup_test_db();

        let root_id = crate::repo::insert_test_root(&conn, "/photos", "source", false);
        insert_source(&conn, root_id, "deleted.jpg", None, false, false); // present=0

        let result = fetch_by_path(&conn, root_id, "deleted.jpg").unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn fetch_by_path_not_found() {
        let conn = setup_test_db();

        let root_id = crate::repo::insert_test_root(&conn, "/photos", "source", false);

        let result = fetch_by_path(&conn, root_id, "nonexistent.jpg").unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn fetch_by_path_wrong_root() {
        let conn = setup_test_db();

        let root1 = crate::repo::insert_test_root(&conn, "/photos", "source", false);
        let root2 = crate::repo::insert_test_root(&conn, "/archive", "archive", false);
        insert_source(&conn, root1, "file.jpg", None, true, false);

        // File exists in root1, but we query root2
        let result = fetch_by_path(&conn, root2, "file.jpg").unwrap();
        assert!(result.is_none());
    }

    // =========================================================================
    // fetch_by_inode tests
    // =========================================================================

    #[test]
    fn fetch_by_inode_exists() {
        let conn = setup_test_db();

        let root_id = crate::repo::insert_test_root(&conn, "/photos", "source", false);

        // Insert source with specific device/inode
        conn.execute(
            "INSERT INTO sources (root_id, rel_path, device, inode, size, mtime, partial_hash, scanned_at, last_seen_at, present)
             VALUES (?, 'file.jpg', 100, 12345, 1000, 1700000000, 'hash', 0, 0, 1)",
            rusqlite::params![root_id],
        ).unwrap();

        let result = fetch_by_inode(&conn, 100, 12345).unwrap();
        assert!(result.is_some());
        assert_eq!(result.unwrap().rel_path, "file.jpg");
    }

    #[test]
    fn fetch_by_inode_cross_root() {
        let conn = setup_test_db();

        let root1 = crate::repo::insert_test_root(&conn, "/photos", "source", false);
        let _root2 = crate::repo::insert_test_root(&conn, "/archive", "archive", false);

        // Insert source in root1 with specific device/inode
        conn.execute(
            "INSERT INTO sources (root_id, rel_path, device, inode, size, mtime, partial_hash, scanned_at, last_seen_at, present)
             VALUES (?, 'original.jpg', 100, 12345, 1000, 1700000000, 'hash', 0, 0, 1)",
            rusqlite::params![root1],
        ).unwrap();

        // Should find it even though we're not specifying root
        let result = fetch_by_inode(&conn, 100, 12345).unwrap();
        assert!(result.is_some());
        let source = result.unwrap();
        assert_eq!(source.rel_path, "original.jpg");
        assert_eq!(source.root_id, root1);
    }

    #[test]
    fn fetch_by_inode_not_found() {
        let conn = setup_test_db();

        let root_id = crate::repo::insert_test_root(&conn, "/photos", "source", false);
        insert_source(&conn, root_id, "file.jpg", None, true, false);

        // Query for non-existent device/inode
        let result = fetch_by_inode(&conn, 999, 999).unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn fetch_by_inode_not_present() {
        let conn = setup_test_db();

        let root_id = crate::repo::insert_test_root(&conn, "/photos", "source", false);

        // Insert non-present source with specific device/inode
        conn.execute(
            "INSERT INTO sources (root_id, rel_path, device, inode, size, mtime, partial_hash, scanned_at, last_seen_at, present)
             VALUES (?, 'deleted.jpg', 100, 12345, 1000, 1700000000, 'hash', 0, 0, 0)",
            rusqlite::params![root_id],
        ).unwrap();

        // Should not find it (present=0)
        let result = fetch_by_inode(&conn, 100, 12345).unwrap();
        assert!(result.is_none());
    }

    // =========================================================================
    // apply_reconciliation tests
    // =========================================================================

    #[test]
    fn apply_reconciliation_new() {
        let conn = setup_test_db();

        let root_id = crate::repo::insert_test_root(&conn, "/photos", "source", false);

        let observation = FileObservation {
            root_id,
            rel_path: "new_file.jpg".to_string(),
            device: 100,
            inode: 12345,
            size: 2048,
            mtime: 1700000000,
            partial_hash: Some("abc123".to_string()),
        };

        let reconciliation = Reconciliation::New;
        let now = 1700000001;

        let source = apply_reconciliation(&conn, &observation, &reconciliation, now).unwrap();

        assert_eq!(source.rel_path, "new_file.jpg");
        assert_eq!(source.size, 2048);
        assert_eq!(source.mtime, 1700000000);
        assert_eq!(source.device, 100);
        assert_eq!(source.inode, 12345);
        assert_eq!(source.partial_hash, "abc123");
        assert_eq!(source.basis_rev, 0);
    }

    #[test]
    fn apply_reconciliation_new_revives_stale_record() {
        // Test: New reconciliation at path where a stale (present=0) record exists
        // The stale record should be revived with new attributes
        let conn = setup_test_db();

        let root_id = crate::repo::insert_test_root(&conn, "/photos", "source", false);

        // Create a stale source at this path (present=0)
        conn.execute(
            "INSERT INTO sources (root_id, rel_path, device, inode, size, mtime, partial_hash, basis_rev, scanned_at, last_seen_at, present, excluded)
             VALUES (?, 'revived.jpg', 1, 1, 500, 1600000000, 'oldhash', 5, 0, 0, 0, 0)",
            rusqlite::params![root_id],
        ).unwrap();
        let old_id = conn.last_insert_rowid();

        let observation = FileObservation {
            root_id,
            rel_path: "revived.jpg".to_string(),
            device: 100,
            inode: 12345,
            size: 2048,
            mtime: 1700000000,
            partial_hash: Some("newhash".to_string()),
        };

        let reconciliation = Reconciliation::New;
        let now = 1700000001;

        let source = apply_reconciliation(&conn, &observation, &reconciliation, now).unwrap();

        // Should revive the same record
        assert_eq!(source.id, old_id);
        assert_eq!(source.rel_path, "revived.jpg");
        // Should have new file's attributes
        assert_eq!(source.device, 100);
        assert_eq!(source.inode, 12345);
        assert_eq!(source.size, 2048);
        assert_eq!(source.mtime, 1700000000);
        assert_eq!(source.partial_hash, "newhash");
        // basis_rev should be reset to 0 (new file)
        assert_eq!(source.basis_rev, 0);
        // object_id should be cleared
        assert_eq!(source.object_id, None);

        // Verify only one record exists
        let count: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM sources WHERE root_id = ? AND rel_path = ?",
                rusqlite::params![root_id, "revived.jpg"],
                |r| r.get(0),
            )
            .unwrap();
        assert_eq!(count, 1);
    }

    #[test]
    fn apply_reconciliation_unchanged() {
        let conn = setup_test_db();

        let root_id = crate::repo::insert_test_root(&conn, "/photos", "source", false);
        let source_id = insert_source(&conn, root_id, "existing.jpg", None, true, false);

        let observation = FileObservation {
            root_id,
            rel_path: "existing.jpg".to_string(),
            device: 0,
            inode: 0,
            size: 1000,
            mtime: 1704067200,
            partial_hash: None,
        };

        let reconciliation = Reconciliation::Unchanged { source_id };
        let now = 1700000001;

        let source = apply_reconciliation(&conn, &observation, &reconciliation, now).unwrap();

        assert_eq!(source.id, source_id);
        assert_eq!(source.rel_path, "existing.jpg");

        // Verify last_seen_at was updated
        let last_seen: i64 = conn
            .query_row(
                "SELECT last_seen_at FROM sources WHERE id = ?",
                rusqlite::params![source_id],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(last_seen, now);
    }

    #[test]
    fn apply_reconciliation_modified() {
        let conn = setup_test_db();

        let root_id = crate::repo::insert_test_root(&conn, "/photos", "source", false);

        // Insert existing source with basis_rev=2
        conn.execute(
            "INSERT INTO sources (root_id, rel_path, device, inode, size, mtime, partial_hash, basis_rev, scanned_at, last_seen_at, present)
             VALUES (?, 'modified.jpg', 100, 12345, 1000, 1700000000, 'oldhash', 2, 0, 0, 1)",
            rusqlite::params![root_id],
        ).unwrap();
        let source_id = conn.last_insert_rowid();

        let observation = FileObservation {
            root_id,
            rel_path: "modified.jpg".to_string(),
            device: 100,
            inode: 12345,
            size: 2048,        // Changed
            mtime: 1700000100, // Changed
            partial_hash: Some("newhash".to_string()),
        };

        let reconciliation = Reconciliation::Modified {
            source_id,
            old_object_id: None,
        };
        let now = 1700000101;

        let source = apply_reconciliation(&conn, &observation, &reconciliation, now).unwrap();

        assert_eq!(source.id, source_id);
        assert_eq!(source.size, 2048);
        assert_eq!(source.mtime, 1700000100);
        assert_eq!(source.partial_hash, "newhash");
        assert_eq!(source.basis_rev, 3); // Incremented from 2
    }

    #[test]
    fn apply_reconciliation_moved() {
        let conn = setup_test_db();

        let root1 = crate::repo::insert_test_root(&conn, "/photos", "source", false);
        let root2 = crate::repo::insert_test_root(&conn, "/archive", "archive", false);

        // Insert existing source in root1
        conn.execute(
            "INSERT INTO sources (root_id, rel_path, device, inode, size, mtime, partial_hash, basis_rev, scanned_at, last_seen_at, present)
             VALUES (?, 'old_location.jpg', 100, 12345, 1000, 1700000000, 'hash123', 1, 0, 0, 1)",
            rusqlite::params![root1],
        ).unwrap();
        let source_id = conn.last_insert_rowid();

        // Observation at new location in root2
        let observation = FileObservation {
            root_id: root2,
            rel_path: "new_location.jpg".to_string(),
            device: 100,
            inode: 12345,
            size: 1000,
            mtime: 1700000000,
            partial_hash: None,
        };

        let reconciliation = Reconciliation::Moved {
            source_id,
            from_root_id: root1,
            from_path: "old_location.jpg".to_string(),
            old_object_id: None,
        };
        let now = 1700000001;

        let source = apply_reconciliation(&conn, &observation, &reconciliation, now).unwrap();

        assert_eq!(source.id, source_id);
        assert_eq!(source.root_id, root2); // Moved to new root
        assert_eq!(source.rel_path, "new_location.jpg"); // New path
        assert_eq!(source.root_path, "/archive"); // Joined field updated
    }

    #[test]
    fn apply_reconciliation_new_requires_partial_hash() {
        let conn = setup_test_db();

        let root_id = crate::repo::insert_test_root(&conn, "/photos", "source", false);

        let observation = FileObservation {
            root_id,
            rel_path: "new_file.jpg".to_string(),
            device: 100,
            inode: 12345,
            size: 2048,
            mtime: 1700000000,
            partial_hash: None, // Missing!
        };

        let reconciliation = Reconciliation::New;
        let now = 1700000001;

        let result = apply_reconciliation(&conn, &observation, &reconciliation, now);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("partial_hash"));
    }

    // =========================================================================
    // mark_missing tests
    // =========================================================================

    #[test]
    fn mark_missing_sets_present_zero() {
        let conn = setup_test_db();

        let root_id = crate::repo::insert_test_root(&conn, "/photos", "source", false);
        let id1 = insert_source(&conn, root_id, "missing1.jpg", None, true, false);
        let id2 = insert_source(&conn, root_id, "missing2.jpg", None, true, false);
        let _id3 = insert_source(&conn, root_id, "present.jpg", None, true, false);

        let now = 1700000001;
        let count = mark_missing(&conn, &[id1, id2], now).unwrap();

        assert_eq!(count, 2);

        // Verify they are now present=0
        let present1: i64 = conn
            .query_row(
                "SELECT present FROM sources WHERE id = ?",
                rusqlite::params![id1],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(present1, 0);

        // Verify present.jpg is still present=1
        let present3: i64 = conn
            .query_row(
                "SELECT present FROM sources WHERE rel_path = 'present.jpg'",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(present3, 1);
    }

    #[test]
    fn mark_missing_empty_list() {
        let conn = setup_test_db();
        let count = mark_missing(&conn, &[], 1700000001).unwrap();
        assert_eq!(count, 0);
    }

    #[test]
    fn mark_missing_returns_count() {
        let conn = setup_test_db();

        let root_id = crate::repo::insert_test_root(&conn, "/photos", "source", false);
        let id1 = insert_source(&conn, root_id, "file1.jpg", None, true, false);
        let id2 = insert_source(&conn, root_id, "file2.jpg", None, false, false); // already not present

        // Only id1 should be updated (id2 is already present=0)
        let count = mark_missing(&conn, &[id1, id2], 1700000001).unwrap();
        assert_eq!(count, 1);
    }

    #[test]
    fn mark_missing_updates_last_seen_at() {
        let conn = setup_test_db();

        let root_id = crate::repo::insert_test_root(&conn, "/photos", "source", false);
        let id1 = insert_source(&conn, root_id, "file.jpg", None, true, false);

        let now = 1700000001;
        mark_missing(&conn, &[id1], now).unwrap();

        let last_seen: i64 = conn
            .query_row(
                "SELECT last_seen_at FROM sources WHERE id = ?",
                rusqlite::params![id1],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(last_seen, now);
    }

    // =========================================================================
    // fetch_source_ids_for_root tests
    // =========================================================================

    #[test]
    fn fetch_source_ids_for_root_returns_present_only() {
        let conn = setup_test_db();

        let root_id = crate::repo::insert_test_root(&conn, "/photos", "source", false);
        let id1 = insert_source(&conn, root_id, "present1.jpg", None, true, false);
        let id2 = insert_source(&conn, root_id, "present2.jpg", None, true, false);
        let _id3 = insert_source(&conn, root_id, "deleted.jpg", None, false, false);

        let ids = fetch_source_ids_for_root(&conn, root_id, None).unwrap();

        assert_eq!(ids.len(), 2);
        assert!(ids.contains(&id1));
        assert!(ids.contains(&id2));
    }

    #[test]
    fn fetch_source_ids_for_root_empty() {
        let conn = setup_test_db();

        let root_id = crate::repo::insert_test_root(&conn, "/photos", "source", false);

        let ids = fetch_source_ids_for_root(&conn, root_id, None).unwrap();
        assert!(ids.is_empty());
    }

    #[test]
    fn fetch_source_ids_for_root_with_prefix() {
        let conn = setup_test_db();

        let root_id = crate::repo::insert_test_root(&conn, "/photos", "source", false);
        let id1 = insert_source(&conn, root_id, "2024/photo1.jpg", None, true, false);
        let id2 = insert_source(&conn, root_id, "2024/photo2.jpg", None, true, false);
        let id3 = insert_source(&conn, root_id, "2023/old.jpg", None, true, false);
        let _id4 = insert_source(&conn, root_id, "2024/deleted.jpg", None, false, false);

        // With prefix, only 2024/* present sources
        let ids = fetch_source_ids_for_root(&conn, root_id, Some("2024/")).unwrap();
        assert_eq!(ids.len(), 2);
        assert!(ids.contains(&id1));
        assert!(ids.contains(&id2));

        // Without prefix, all present sources
        let all_ids = fetch_source_ids_for_root(&conn, root_id, None).unwrap();
        assert_eq!(all_ids.len(), 3);
        assert!(all_ids.contains(&id3));
    }

    // =========================================================================
    // set_excluded tests
    // =========================================================================

    #[test]
    fn set_excluded_marks_source() {
        let conn = setup_test_db();

        let root_id = crate::repo::insert_test_root(&conn, "/photos", "source", false);
        let source_id = insert_source(&conn, root_id, "file.jpg", None, true, false);

        // Verify initially not excluded
        let excluded: i64 = conn
            .query_row(
                "SELECT excluded FROM sources WHERE id = ?",
                rusqlite::params![source_id],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(excluded, 0);

        // Set excluded
        set_excluded(&conn, source_id, true).unwrap();

        // Verify now excluded
        let excluded: i64 = conn
            .query_row(
                "SELECT excluded FROM sources WHERE id = ?",
                rusqlite::params![source_id],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(excluded, 1);
    }

    #[test]
    fn set_excluded_clears_source() {
        let conn = setup_test_db();

        let root_id = crate::repo::insert_test_root(&conn, "/photos", "source", false);
        let source_id = insert_source(&conn, root_id, "file.jpg", None, true, true); // starts excluded

        // Verify initially excluded
        let excluded: i64 = conn
            .query_row(
                "SELECT excluded FROM sources WHERE id = ?",
                rusqlite::params![source_id],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(excluded, 1);

        // Clear excluded
        set_excluded(&conn, source_id, false).unwrap();

        // Verify now not excluded
        let excluded: i64 = conn
            .query_row(
                "SELECT excluded FROM sources WHERE id = ?",
                rusqlite::params![source_id],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(excluded, 0);
    }

    #[test]
    fn set_excluded_nonexistent_source() {
        let conn = setup_test_db();

        // Should not error when source doesn't exist
        let result = set_excluded(&conn, 99999, true);
        assert!(result.is_ok());
    }

    // =========================================================================
    // batch_set_excluded tests
    // =========================================================================

    #[test]
    fn batch_set_excluded_empty_list() {
        let conn = setup_test_db();
        let count = batch_set_excluded(&conn, &[], true).unwrap();
        assert_eq!(count, 0);
    }

    #[test]
    fn batch_set_excluded_multiple() {
        let conn = setup_test_db();

        let root_id = crate::repo::insert_test_root(&conn, "/photos", "source", false);
        let id1 = insert_source(&conn, root_id, "file1.jpg", None, true, false);
        let id2 = insert_source(&conn, root_id, "file2.jpg", None, true, false);
        let id3 = insert_source(&conn, root_id, "file3.jpg", None, true, false);

        // Exclude id1 and id2, leave id3
        let count = batch_set_excluded(&conn, &[id1, id2], true).unwrap();
        assert_eq!(count, 2);

        // Verify exclusion state
        let excluded1: i64 = conn
            .query_row(
                "SELECT excluded FROM sources WHERE id = ?",
                rusqlite::params![id1],
                |row| row.get(0),
            )
            .unwrap();
        let excluded2: i64 = conn
            .query_row(
                "SELECT excluded FROM sources WHERE id = ?",
                rusqlite::params![id2],
                |row| row.get(0),
            )
            .unwrap();
        let excluded3: i64 = conn
            .query_row(
                "SELECT excluded FROM sources WHERE id = ?",
                rusqlite::params![id3],
                |row| row.get(0),
            )
            .unwrap();

        assert_eq!(excluded1, 1);
        assert_eq!(excluded2, 1);
        assert_eq!(excluded3, 0); // Not in the batch
    }

    #[test]
    fn batch_set_excluded_returns_count() {
        let conn = setup_test_db();

        let root_id = crate::repo::insert_test_root(&conn, "/photos", "source", false);
        let id1 = insert_source(&conn, root_id, "file1.jpg", None, true, false);
        let _id2 = insert_source(&conn, root_id, "file2.jpg", None, true, false);

        // Request update for id1 and a nonexistent id
        let count = batch_set_excluded(&conn, &[id1, 99999], true).unwrap();

        // Only id1 should be updated
        assert_eq!(count, 1);
    }

    #[test]
    fn batch_set_excluded_skips_nonexistent() {
        let conn = setup_test_db();

        let root_id = crate::repo::insert_test_root(&conn, "/photos", "source", false);
        let id1 = insert_source(&conn, root_id, "file.jpg", None, true, false);

        // Mix of existing and nonexistent IDs
        let count = batch_set_excluded(&conn, &[id1, 99998, 99999], true).unwrap();

        // Only the existing source should be updated
        assert_eq!(count, 1);

        // Verify it was actually updated
        let excluded: i64 = conn
            .query_row(
                "SELECT excluded FROM sources WHERE id = ?",
                rusqlite::params![id1],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(excluded, 1);
    }

    #[test]
    fn batch_set_excluded_handles_large_batch() {
        let conn = setup_test_db();

        let root_id = crate::repo::insert_test_root(&conn, "/photos", "source", false);

        // Create more than BATCH_SIZE sources (1000+)
        let mut source_ids = Vec::new();
        for i in 0..1050 {
            let id = insert_source(
                &conn,
                root_id,
                &format!("file_{i}.jpg"),
                None,
                true,
                false,
            );
            source_ids.push(id);
        }

        // Exclude all of them
        let count = batch_set_excluded(&conn, &source_ids, true).unwrap();
        assert_eq!(count, 1050);

        // Verify a sample from each batch chunk
        let excluded_first: i64 = conn
            .query_row(
                "SELECT excluded FROM sources WHERE id = ?",
                rusqlite::params![source_ids[0]],
                |row| row.get(0),
            )
            .unwrap();
        let excluded_mid: i64 = conn
            .query_row(
                "SELECT excluded FROM sources WHERE id = ?",
                rusqlite::params![source_ids[500]],
                |row| row.get(0),
            )
            .unwrap();
        let excluded_last: i64 = conn
            .query_row(
                "SELECT excluded FROM sources WHERE id = ?",
                rusqlite::params![source_ids[1049]],
                |row| row.get(0),
            )
            .unwrap();

        assert_eq!(excluded_first, 1);
        assert_eq!(excluded_mid, 1);
        assert_eq!(excluded_last, 1);
    }

    // =========================================================================
    // batch_check_paths_exist tests
    // =========================================================================

    #[test]
    fn batch_check_paths_exist_empty_input() {
        let conn = setup_test_db();
        let _root_id = crate::repo::insert_test_root(&conn, "/archive", "archive", false);
        let result = batch_check_paths_exist(&conn, 1, &[]).unwrap();
        assert!(result.is_empty());
    }

    #[test]
    fn batch_check_paths_exist_none_found() {
        let conn = setup_test_db();
        let root_id = crate::repo::insert_test_root(&conn, "/archive", "archive", false);

        // No sources exist, query for paths that don't exist
        let result = batch_check_paths_exist(&conn, root_id, &["a.jpg", "b.jpg"]).unwrap();
        assert!(result.is_empty());
    }

    #[test]
    fn batch_check_paths_exist_all_found() {
        let conn = setup_test_db();
        let root_id = crate::repo::insert_test_root(&conn, "/archive", "archive", false);

        insert_source(&conn, root_id, "a.jpg", None, true, false);
        insert_source(&conn, root_id, "b.jpg", None, true, false);

        let result = batch_check_paths_exist(&conn, root_id, &["a.jpg", "b.jpg"]).unwrap();
        assert_eq!(result.len(), 2);
        assert!(result.contains("a.jpg"));
        assert!(result.contains("b.jpg"));
    }

    #[test]
    fn batch_check_paths_exist_mixed() {
        let conn = setup_test_db();
        let root_id = crate::repo::insert_test_root(&conn, "/archive", "archive", false);

        insert_source(&conn, root_id, "exists.jpg", None, true, false);
        // "missing.jpg" is not inserted

        let result =
            batch_check_paths_exist(&conn, root_id, &["exists.jpg", "missing.jpg"]).unwrap();
        assert_eq!(result.len(), 1);
        assert!(result.contains("exists.jpg"));
        assert!(!result.contains("missing.jpg"));
    }

    #[test]
    fn batch_check_paths_exist_ignores_not_present() {
        let conn = setup_test_db();
        let root_id = crate::repo::insert_test_root(&conn, "/archive", "archive", false);

        insert_source(&conn, root_id, "present.jpg", None, true, false);
        insert_source(&conn, root_id, "deleted.jpg", None, false, false); // present=0

        let result =
            batch_check_paths_exist(&conn, root_id, &["present.jpg", "deleted.jpg"]).unwrap();
        assert_eq!(result.len(), 1);
        assert!(result.contains("present.jpg"));
        assert!(!result.contains("deleted.jpg"));
    }

    #[test]
    fn batch_check_paths_exist_different_root() {
        let conn = setup_test_db();
        let root1 = crate::repo::insert_test_root(&conn, "/archive1", "archive", false);
        let root2 = crate::repo::insert_test_root(&conn, "/archive2", "archive", false);

        // Insert in root1
        insert_source(&conn, root1, "file.jpg", None, true, false);

        // Query against root2 - should not find it
        let result = batch_check_paths_exist(&conn, root2, &["file.jpg"]).unwrap();
        assert!(result.is_empty());

        // Query against root1 - should find it
        let result = batch_check_paths_exist(&conn, root1, &["file.jpg"]).unwrap();
        assert_eq!(result.len(), 1);
        assert!(result.contains("file.jpg"));
    }

    #[test]
    fn batch_check_paths_exist_handles_999_paths() {
        let conn = setup_test_db();
        let root_id = crate::repo::insert_test_root(&conn, "/archive", "archive", false);

        // Create 999 sources (just under BATCH_SIZE)
        let mut paths = Vec::new();
        for i in 0..999 {
            let path = format!("file_{i}.jpg");
            insert_source(&conn, root_id, &path, None, true, false);
            paths.push(path);
        }

        let path_refs: Vec<&str> = paths.iter().map(|s| s.as_str()).collect();
        let result = batch_check_paths_exist(&conn, root_id, &path_refs).unwrap();

        assert_eq!(result.len(), 999);
    }

    #[test]
    fn batch_check_paths_exist_handles_1000_paths() {
        let conn = setup_test_db();
        let root_id = crate::repo::insert_test_root(&conn, "/archive", "archive", false);

        // Create exactly BATCH_SIZE sources
        let mut paths = Vec::new();
        for i in 0..1000 {
            let path = format!("file_{i}.jpg");
            insert_source(&conn, root_id, &path, None, true, false);
            paths.push(path);
        }

        let path_refs: Vec<&str> = paths.iter().map(|s| s.as_str()).collect();
        let result = batch_check_paths_exist(&conn, root_id, &path_refs).unwrap();

        assert_eq!(result.len(), 1000);
    }

    #[test]
    fn batch_check_paths_exist_handles_1001_paths() {
        let conn = setup_test_db();
        let root_id = crate::repo::insert_test_root(&conn, "/archive", "archive", false);

        // Create more than BATCH_SIZE sources (requires 2 batches)
        let mut paths = Vec::new();
        for i in 0..1001 {
            let path = format!("file_{i}.jpg");
            insert_source(&conn, root_id, &path, None, true, false);
            paths.push(path);
        }

        let path_refs: Vec<&str> = paths.iter().map(|s| s.as_str()).collect();
        let result = batch_check_paths_exist(&conn, root_id, &path_refs).unwrap();

        assert_eq!(result.len(), 1001);

        // Verify samples from both batches
        assert!(result.contains("file_0.jpg"));
        assert!(result.contains("file_999.jpg"));
        assert!(result.contains("file_1000.jpg"));
    }

    // =========================================================================
    // count_unhashed_for_root tests
    // =========================================================================

    #[test]
    fn count_unhashed_for_root_empty() {
        let conn = setup_test_db();
        let root_id = crate::repo::insert_test_root(&conn, "/archive", "archive", false);

        let (total, unhashed) = count_unhashed_for_root(&conn, root_id).unwrap();
        assert_eq!(total, 0);
        assert_eq!(unhashed, 0);
    }

    #[test]
    fn count_unhashed_for_root_all_hashed() {
        let conn = setup_test_db();
        let root_id = crate::repo::insert_test_root(&conn, "/archive", "archive", false);
        let obj_id = insert_object(&conn, "abc123", false);

        // Insert 3 sources, all with object_id
        insert_source(&conn, root_id, "a.jpg", Some(obj_id), true, false);
        insert_source(&conn, root_id, "b.jpg", Some(obj_id), true, false);
        insert_source(&conn, root_id, "c.jpg", Some(obj_id), true, false);

        let (total, unhashed) = count_unhashed_for_root(&conn, root_id).unwrap();
        assert_eq!(total, 3);
        assert_eq!(unhashed, 0);
    }

    #[test]
    fn count_unhashed_for_root_some_unhashed() {
        let conn = setup_test_db();
        let root_id = crate::repo::insert_test_root(&conn, "/archive", "archive", false);
        let obj_id = insert_object(&conn, "abc123", false);

        // 2 hashed, 1 unhashed
        insert_source(&conn, root_id, "a.jpg", Some(obj_id), true, false);
        insert_source(&conn, root_id, "b.jpg", Some(obj_id), true, false);
        insert_source(&conn, root_id, "c.jpg", None, true, false); // No object_id

        let (total, unhashed) = count_unhashed_for_root(&conn, root_id).unwrap();
        assert_eq!(total, 3);
        assert_eq!(unhashed, 1);
    }

    #[test]
    fn count_unhashed_for_root_excludes_not_present() {
        let conn = setup_test_db();
        let root_id = crate::repo::insert_test_root(&conn, "/archive", "archive", false);

        // 1 present without hash, 1 not present without hash
        insert_source(&conn, root_id, "present.jpg", None, true, false);
        insert_source(&conn, root_id, "deleted.jpg", None, false, false); // present=0

        let (total, unhashed) = count_unhashed_for_root(&conn, root_id).unwrap();
        assert_eq!(total, 1); // Only present sources
        assert_eq!(unhashed, 1);
    }

    // =========================================================================
    // update_location tests
    // =========================================================================

    #[test]
    fn update_location_updates_fields() {
        let conn = setup_test_db();

        let source_root = crate::repo::insert_test_root(&conn, "/photos", "source", false);
        let archive_root = crate::repo::insert_test_root(&conn, "/archive", "archive", false);
        let source_id = insert_source(&conn, source_root, "original.jpg", None, true, false);

        let now = 1700000001i64;
        update_location(&conn, source_id, archive_root, "new/path.jpg", now).unwrap();

        // Verify fields updated
        let (root_id, rel_path, scanned_at, last_seen_at): (i64, String, i64, i64) = conn
            .query_row(
                "SELECT root_id, rel_path, scanned_at, last_seen_at FROM sources WHERE id = ?",
                rusqlite::params![source_id],
                |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),
            )
            .unwrap();

        assert_eq!(root_id, archive_root);
        assert_eq!(rel_path, "new/path.jpg");
        assert_eq!(scanned_at, now);
        assert_eq!(last_seen_at, now);
    }

    #[test]
    fn update_location_nonexistent_source() {
        let conn = setup_test_db();
        let root_id = crate::repo::insert_test_root(&conn, "/archive", "archive", false);

        // Should not error when source doesn't exist (0 rows affected)
        let result = update_location(&conn, 99999, root_id, "path.jpg", 1700000001);
        assert!(result.is_ok());
    }

    // =========================================================================
    // fetch_device_info_by_prefix tests
    // =========================================================================

    #[test]
    fn fetch_device_info_by_prefix_empty_root() {
        let conn = setup_test_db();
        let root_id = crate::repo::insert_test_root(&conn, "/photos", "source", false);

        let results = fetch_device_info_by_prefix(&conn, root_id, "").unwrap();
        assert!(results.is_empty());
    }

    #[test]
    fn fetch_device_info_by_prefix_matches_all() {
        let conn = setup_test_db();
        let root_id = crate::repo::insert_test_root(&conn, "/photos", "source", false);

        // Insert sources with different devices
        insert_test_source(&conn, root_id, "a/1.jpg", 100, 1, 1000, 1700000000);
        insert_test_source(&conn, root_id, "a/2.jpg", 100, 2, 1000, 1700000000);
        insert_test_source(&conn, root_id, "b/3.jpg", 200, 3, 1000, 1700000000);

        // Empty prefix matches all
        let results = fetch_device_info_by_prefix(&conn, root_id, "").unwrap();
        assert_eq!(results.len(), 3);
    }

    #[test]
    fn fetch_device_info_by_prefix_matches_prefix() {
        let conn = setup_test_db();
        let root_id = crate::repo::insert_test_root(&conn, "/photos", "source", false);

        insert_test_source(&conn, root_id, "a/1.jpg", 100, 1, 1000, 1700000000);
        insert_test_source(&conn, root_id, "a/2.jpg", 100, 2, 1000, 1700000000);
        insert_test_source(&conn, root_id, "b/3.jpg", 200, 3, 1000, 1700000000);

        // Prefix "a" matches only files under "a/"
        let results = fetch_device_info_by_prefix(&conn, root_id, "a").unwrap();
        assert_eq!(results.len(), 2);
    }

    #[test]
    fn fetch_device_info_by_prefix_excludes_not_present() {
        let conn = setup_test_db();
        let root_id = crate::repo::insert_test_root(&conn, "/photos", "source", false);

        insert_test_source(&conn, root_id, "a/1.jpg", 100, 1, 1000, 1700000000);
        // Mark as not present
        conn.execute(
            "UPDATE sources SET present = 0 WHERE rel_path = 'a/1.jpg'",
            [],
        )
        .unwrap();

        let results = fetch_device_info_by_prefix(&conn, root_id, "").unwrap();
        assert!(results.is_empty());
    }

    #[test]
    fn fetch_device_info_by_prefix_returns_device() {
        let conn = setup_test_db();
        let root_id = crate::repo::insert_test_root(&conn, "/photos", "source", false);

        insert_test_source(&conn, root_id, "a/1.jpg", 12345, 1, 1000, 1700000000);

        let results = fetch_device_info_by_prefix(&conn, root_id, "").unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].1, Some(12345));
    }

    // =========================================================================
    // set_object_id tests
    // =========================================================================

    #[test]
    fn set_object_id_links_source() {
        let conn = setup_test_db();
        let root_id = crate::repo::insert_test_root(&conn, "/photos", "source", false);
        let source_id = insert_source(&conn, root_id, "photo.jpg", None, true, false);
        let object_id = insert_object(&conn, "abc123", false);

        set_object_id(&conn, source_id, object_id).unwrap();

        // Verify source is linked to object
        let stored: i64 = conn
            .query_row(
                "SELECT object_id FROM sources WHERE id = ?",
                [source_id],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(stored, object_id);
    }

    #[test]
    fn set_object_id_nonexistent_source() {
        let conn = setup_test_db();
        let object_id = insert_object(&conn, "abc123", false);

        // Should not error when source doesn't exist
        let result = set_object_id(&conn, 99999, object_id);
        assert!(result.is_ok());
    }
}