crawlrs 0.2.0

crawlrs - Enterprise-grade web scraping and crawling platform built with Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
// Copyright (c) 2025-2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

use super::*;
use crate::common::test_helpers::acquire_next_test_mutex;
use crate::common::test_helpers::create_test_db_pool;
use crate::domain::models::{Task, TaskType};
use chrono::Duration;
use serde_json::json;

/// Build a minimal Task instance for tests.
/// Each call produces fresh UUIDs for id/team_id/api_key_id so tests are isolated.
fn make_test_task() -> Task {
    Task::new(
        crate::domain::id::Id::generate(),
        TaskType::Scrape,
        crate::domain::id::Id::generate(),
        crate::domain::id::Id::generate(),
        "http://example.com".to_string(),
        json!({}),
    )
}

/// Build a Task with a unique URL (for exists_by_url / find_existing_urls tests).
fn make_test_task_with_unique_url() -> Task {
    let mut task = make_test_task();
    task.url = format!("http://example.com/{}", crate::domain::id::Id::generate());
    task
}

// Construction tests (real DB pool)

#[test]
fn test_new_creates_repository_instance() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let pool = create_test_db_pool();
    let repo = TaskRepositoryImpl::new(pool, Duration::minutes(5));
    // Repository should be constructible with a real pool
    let _ = repo;
}

// CRUD tests — verify create / find / update / state transitions
// against a real PostgreSQL database.

#[tokio::test]
async fn test_create_with_real_db_succeeds() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    // 序列化:防止并行的 acquire_next 测试偷走本测试创建的 queued 任务,
    // 导致 find_by_id 读回 status=Active 而非 Queued(测试隔离修复)
    let _guard = acquire_next_test_mutex().lock().await;
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    let task = make_test_task();
    let result = repo.create(&task).await;
    assert!(result.is_ok(), "create failed: {:?}", result.err());
    let returned = result.unwrap();
    assert_eq!(returned.id, task.id);
    assert_eq!(returned.url, task.url);
    assert_eq!(returned.team_id, task.team_id);

    // Verify DB state actually changed
    let found = repo.find_by_id(task.id).await.expect("find_by_id failed");
    assert!(found.is_some(), "task should be found after create");
    let found_task = found.unwrap();
    assert_eq!(found_task.id, task.id);
    assert_eq!(found_task.url, task.url);
    assert_eq!(found_task.task_type, task.task_type);
    assert_eq!(found_task.team_id, task.team_id);
    assert_eq!(found_task.status, task.status);
}

#[tokio::test]
async fn test_find_by_id_with_real_db_returns_none_for_unknown() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    let result = repo.find_by_id(crate::domain::id::Id::generate()).await;
    assert!(result.is_ok(), "find_by_id failed: {:?}", result.err());
    assert!(result.unwrap().is_none(), "unknown UUID should return None");
}

#[tokio::test]
async fn test_update_with_real_db_succeeds() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    let mut task = make_test_task();
    // create first
    repo.create(&task).await.expect("create failed");
    // modify fields and update
    task.url = format!("http://updated.com/{}", crate::domain::id::Id::generate());
    task.priority = 7;
    task.payload = json!({"updated": true});
    let result = repo.update(&task).await;
    assert!(result.is_ok(), "update failed: {:?}", result.err());

    // Verify DB state reflects updated fields
    let found = repo
        .find_by_id(task.id)
        .await
        .expect("find_by_id failed")
        .expect("task should exist");
    assert_eq!(found.url, task.url);
    assert_eq!(found.priority, 7);
    assert_eq!(found.payload, json!({"updated": true}));
}

#[tokio::test]
async fn test_acquire_next_with_real_db_returns_ok_when_backlog_empty() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    // 序列化 acquire_next 测试:防止并行测试间相互获取 task
    let _guard = acquire_next_test_mutex().lock().await;
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    // No queued tasks with this worker_id; backlog should be empty (or
    // only contain other tests' tasks with different team_id, but acquire_next
    // does not filter by team_id — to be safe we use a fresh worker_id and
    // accept that if some other test left a queued task it might be acquired).
    let result = repo.acquire_next(crate::domain::id::Id::generate()).await;
    assert!(result.is_ok(), "acquire_next failed: {:?}", result.err());
    // We cannot assert None strongly because the shared test DB may have
    // queued tasks from other tests. We at least verify it returns Ok.
    let _ = result.unwrap();
}

#[tokio::test]
async fn test_acquire_next_with_real_db_acquires_created_task() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    // 序列化 acquire_next 测试:防止并行测试间相互获取 task
    let _guard = acquire_next_test_mutex().lock().await;
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    // 创建最高优先级的 queued task(SQL ORDER BY priority ASC,0 = 最高优先级)
    let mut task = make_test_task();
    task.priority = 0;
    repo.create(&task).await.expect("create failed");

    let worker = crate::domain::id::Id::generate();
    let result = repo.acquire_next(worker).await;
    assert!(result.is_ok(), "acquire_next failed: {:?}", result.err());
    let acquired = result.unwrap();
    assert!(acquired.is_some(), "should acquire the queued task");
    let acquired_task = acquired.unwrap();
    assert_eq!(acquired_task.status, TaskStatus::Active);
    assert_eq!(acquired_task.lock_token, Some(worker));
    assert!(acquired_task.lock_expires_at.is_some());
    assert!(acquired_task.started_at.is_some());
}

#[tokio::test]
async fn test_mark_completed_with_real_db_succeeds() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    let task = make_test_task();
    repo.create(&task).await.expect("create failed");

    let result = repo.mark_completed(task.id, None).await;
    assert!(result.is_ok(), "mark_completed failed: {:?}", result.err());

    let found = repo
        .find_by_id(task.id)
        .await
        .expect("find_by_id failed")
        .expect("task should exist");
    assert_eq!(found.status, TaskStatus::Completed);
    assert!(found.completed_at.is_some());
}

#[tokio::test]
async fn test_mark_failed_with_real_db_succeeds() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    let task = make_test_task();
    repo.create(&task).await.expect("create failed");

    let result = repo.mark_failed(task.id, None).await;
    assert!(result.is_ok(), "mark_failed failed: {:?}", result.err());

    let found = repo
        .find_by_id(task.id)
        .await
        .expect("find_by_id failed")
        .expect("task should exist");
    assert_eq!(found.status, TaskStatus::Failed);
    assert!(found.completed_at.is_some());
}

#[tokio::test]
async fn test_mark_cancelled_with_real_db_succeeds() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    let task = make_test_task();
    repo.create(&task).await.expect("create failed");

    let result = repo.mark_cancelled(task.id).await;
    assert!(result.is_ok(), "mark_cancelled failed: {:?}", result.err());

    let found = repo
        .find_by_id(task.id)
        .await
        .expect("find_by_id failed")
        .expect("task should exist");
    assert_eq!(found.status, TaskStatus::Cancelled);
    assert!(found.completed_at.is_some());
}

#[tokio::test]
async fn test_exists_by_url_with_real_db_returns_false_for_unknown() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    let unknown_url = format!(
        "http://nonexistent-{}.com",
        crate::domain::id::Id::generate()
    );
    let result = repo.exists_by_url(&unknown_url).await;
    assert!(result.is_ok(), "exists_by_url failed: {:?}", result.err());
    assert!(!result.unwrap(), "unknown URL should return false");
}

#[tokio::test]
async fn test_exists_by_url_with_real_db_returns_true_for_existing() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    let task = make_test_task_with_unique_url();
    repo.create(&task).await.expect("create failed");

    let result = repo.exists_by_url(&task.url).await;
    assert!(result.is_ok(), "exists_by_url failed: {:?}", result.err());
    assert!(result.unwrap(), "existing URL should return true");
}

#[tokio::test]
async fn test_find_existing_urls_returns_empty_for_empty_input() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    // Empty input should short-circuit to Ok(empty set) without DB access
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    let result = repo.find_existing_urls(&[]).await;
    assert!(result.is_ok());
    assert!(result.unwrap().is_empty());
}

#[tokio::test]
async fn test_find_existing_urls_with_real_db_returns_empty_for_unknown() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    let urls = vec![format!(
        "http://nonexistent-{}.com",
        crate::domain::id::Id::generate()
    )];
    let result = repo.find_existing_urls(&urls).await;
    assert!(
        result.is_ok(),
        "find_existing_urls failed: {:?}",
        result.err()
    );
    assert!(
        result.unwrap().is_empty(),
        "unknown URLs should return empty set"
    );
}

#[tokio::test]
async fn test_find_existing_urls_with_real_db_returns_matching_urls() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    let task1 = make_test_task_with_unique_url();
    let task2 = make_test_task_with_unique_url();
    repo.create(&task1).await.expect("create task1 failed");
    repo.create(&task2).await.expect("create task2 failed");

    let unknown_url = format!(
        "http://nonexistent-{}.com",
        crate::domain::id::Id::generate()
    );
    let urls = vec![task1.url.clone(), task2.url.clone(), unknown_url.clone()];
    let result = repo.find_existing_urls(&urls).await;
    assert!(
        result.is_ok(),
        "find_existing_urls failed: {:?}",
        result.err()
    );
    let existing = result.unwrap();
    assert_eq!(existing.len(), 2, "should find both created URLs");
    assert!(existing.contains(&task1.url));
    assert!(existing.contains(&task2.url));
    assert!(!existing.contains(&unknown_url));
}

#[tokio::test]
async fn test_reset_stuck_tasks_with_real_db_returns_zero_when_none_stuck() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    let result = repo.reset_stuck_tasks(Duration::minutes(30)).await;
    assert!(
        result.is_ok(),
        "reset_stuck_tasks failed: {:?}",
        result.err()
    );
    // No tasks have been stuck for 30min in a fresh test DB.
    // (Other tests may have created Active tasks, but they were just created.)
    let _count = result.unwrap();
}

#[tokio::test]
async fn test_reset_stuck_tasks_with_real_db_resets_stuck_task() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    let mut task = make_test_task();
    // Force task into Active state with an old started_at to be considered stuck.
    task.status = TaskStatus::Active;
    task.started_at = Some(Utc::now() - Duration::hours(2));
    task.updated_at = Utc::now() - Duration::hours(2);
    repo.create(&task).await.expect("create failed");

    let result = repo.reset_stuck_tasks(Duration::minutes(30)).await;
    assert!(
        result.is_ok(),
        "reset_stuck_tasks failed: {:?}",
        result.err()
    );
    // Note: count may be 0 in parallel test runs if another concurrent test
    // already reset this task via its own reset_stuck_tasks call. The
    // meaningful invariant is that the task ends up in the Queued state
    // with lock fields cleared.
    let _count = result.unwrap();

    let found = repo.find_by_id(task.id).await.expect("find_by_id failed");
    let found_task = found.expect("stuck task must still exist");
    {
        assert_eq!(
            found_task.status,
            TaskStatus::Queued,
            "stuck task should be reset to Queued"
        );
        assert!(found_task.started_at.is_none());
        assert!(found_task.lock_token.is_none());
        assert!(found_task.lock_expires_at.is_none());
    }
}

#[tokio::test]
async fn test_cancel_tasks_by_crawl_id_with_real_db_returns_zero_for_unknown() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    let result = repo
        .cancel_tasks_by_crawl_id(crate::domain::id::Id::generate())
        .await;
    assert!(
        result.is_ok(),
        "cancel_tasks_by_crawl_id failed: {:?}",
        result.err()
    );
    assert_eq!(result.unwrap(), 0, "unknown crawl_id should cancel 0 tasks");
}

#[tokio::test]
async fn test_cancel_tasks_by_crawl_id_with_real_db_cancels_matching() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    let crawl_id = crate::domain::id::Id::generate();
    let mut task1 = make_test_task();
    task1.crawl_id = Some(crawl_id);
    let mut task2 = make_test_task();
    task2.crawl_id = Some(crawl_id);
    // 唯一索引 (crawl_id, url):同 crawl 下必须使用不同 URL
    task2.url = format!("{}/task2", task2.url);
    let mut task3 = make_test_task();
    task3.crawl_id = Some(crawl_id);
    task3.url = format!("{}/task3", task3.url);
    task3.status = TaskStatus::Completed; // already completed, should not be cancelled
    repo.create(&task1).await.expect("create task1 failed");
    repo.create(&task2).await.expect("create task2 failed");
    repo.create(&task3).await.expect("create task3 failed");

    let result = repo.cancel_tasks_by_crawl_id(crawl_id).await;
    assert!(result.is_ok(), "cancel_tasks_by_crawl_id failed");
    let count = result.unwrap();
    assert_eq!(count, 2, "should cancel 2 queued/active tasks");

    let found1 = repo
        .find_by_id(task1.id)
        .await
        .expect("find_by_id failed")
        .expect("task1 should exist");
    assert_eq!(found1.status, TaskStatus::Cancelled);
    assert!(
        found1.completed_at.is_some(),
        "cancelled 行必须写 completed_at"
    );
    assert!(found1.lock_token.is_none(), "cancelled 行必须清锁");
    assert!(
        found1.lock_expires_at.is_none(),
        "cancelled 行必须清锁过期时间"
    );
    let found2 = repo
        .find_by_id(task2.id)
        .await
        .expect("find_by_id failed")
        .expect("task2 should exist");
    assert_eq!(found2.status, TaskStatus::Cancelled);
    let found3 = repo
        .find_by_id(task3.id)
        .await
        .expect("find_by_id failed")
        .expect("task3 should exist");
    assert_eq!(
        found3.status,
        TaskStatus::Completed,
        "completed task should not be cancelled"
    );
}

#[tokio::test]
async fn test_expire_tasks_with_real_db_returns_zero_when_none_expired() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    // 序列化:防止 acquire_next 测试获取此测试创建的 queued task
    let _guard = acquire_next_test_mutex().lock().await;
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    // Create a fresh queued task that is not stale (just created).
    let task = make_test_task_with_unique_url();
    repo.create(&task).await.expect("create failed");

    let result = repo.expire_tasks().await;
    assert!(result.is_ok(), "expire_tasks failed: {:?}", result.err());
    // The freshly created task should not be expired (created_at is now,
    // expires_at is None, so it doesn't match any expire condition).
    let _count = result.unwrap();
}

#[tokio::test]
async fn test_expire_tasks_with_real_db_expires_past_expires_at() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    // 序列化:防止 acquire_next 测试获取此测试创建的 queued task(status→active),
    // 导致 expire_tasks 不再匹配 status='queued' 条件
    let _guard = acquire_next_test_mutex().lock().await;
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    let mut task = make_test_task();
    // Set expires_at in the past so the task should be expired.
    task.expires_at = Some(Utc::now() - Duration::minutes(5));
    // 同时持锁:过期终结必须清空锁字段,否则锁心跳仍会续期终态任务。
    task.lock_token = Some(crate::domain::id::Id::generate());
    task.lock_expires_at = Some(Utc::now() - Duration::minutes(1));
    repo.create(&task).await.expect("create failed");

    let result = repo.expire_tasks().await;
    assert!(result.is_ok(), "expire_tasks failed");
    let count = result.unwrap();
    assert!(count >= 1, "at least one task should be expired");

    let found = repo.find_by_id(task.id).await.expect("find_by_id failed");
    let found_task = found.expect("expired task must still exist");
    {
        assert_eq!(
            found_task.status,
            TaskStatus::Failed,
            "expired task should be marked Failed"
        );
        assert!(
            found_task.completed_at.is_some(),
            "expired task must get completed_at"
        );
        assert!(
            found_task.lock_token.is_none(),
            "expired task must clear lock_token"
        );
        assert!(
            found_task.lock_expires_at.is_none(),
            "expired task must clear lock_expires_at"
        );
    }
}

/// 批量过期后 crawl 计数/终态对账:过期子任务必须计入 failed 并使 crawl
/// 进入 failed,而不是永久 queued。
#[tokio::test]
async fn test_expire_tasks_reconciles_crawl_counters_and_status() {
    use crate::domain::models::crawl_model::{Crawl, CrawlStatus};
    use crate::domain::repositories::crawl_repository::CrawlRepository;
    use crate::infrastructure::database::repositories::crawl_repo_impl::CrawlRepositoryImpl;

    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let _guard = acquire_next_test_mutex().lock().await;
    let pool = create_test_db_pool();
    let crawl_repo = CrawlRepositoryImpl::new(pool.clone());
    let crawl_id = crate::domain::id::Id::generate();
    let now = Utc::now();
    let crawl = Crawl::with_all_fields(
        crawl_id,
        crate::domain::id::Id::generate(),
        "expire-reconcile".to_string(),
        "https://example.com/".to_string(),
        "https://example.com/".to_string(),
        CrawlStatus::Queued,
        json!({}),
        1,
        0,
        0,
        now,
        now,
        None,
    );
    crawl_repo
        .create(&crawl)
        .await
        .expect("crawl create failed");

    let repo = TaskRepositoryImpl::new(pool.clone(), Duration::minutes(5));
    let mut task = make_test_task();
    task.crawl_id = Some(crawl_id);
    task.expires_at = Some(Utc::now() - Duration::minutes(5));
    repo.create(&task).await.expect("task create failed");

    repo.expire_tasks().await.expect("expire_tasks failed");

    let crawl = crawl_repo
        .find_by_id(crawl_id)
        .await
        .expect("find crawl failed")
        .expect("crawl must exist");
    assert_eq!(crawl.total_tasks(), 1, "total recomputed from tasks");
    assert_eq!(crawl.failed_tasks(), 1, "expired task counted as failed");
    assert_eq!(crawl.completed_tasks(), 0);
    assert_eq!(
        crawl.status,
        CrawlStatus::Failed,
        "all-failed crawl must be terminal Failed"
    );
    assert!(
        crawl.completed_at.is_some(),
        "terminal crawl gets completed_at"
    );
}

/// 崩溃恢复对账:任务已全部 Completed 但 crawl 计数未自增(worker 硬终止
/// 窗口)时,expire_tasks 用 tasks 实际计数重算并收口终态。
#[tokio::test]
async fn test_expire_tasks_recovers_stuck_crawl_progress_from_tasks() {
    use crate::domain::models::crawl_model::{Crawl, CrawlStatus};
    use crate::domain::repositories::crawl_repository::CrawlRepository;
    use crate::infrastructure::database::repositories::crawl_repo_impl::CrawlRepositoryImpl;

    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let _guard = acquire_next_test_mutex().lock().await;
    let pool = create_test_db_pool();
    let crawl_repo = CrawlRepositoryImpl::new(pool.clone());
    let crawl_id = crate::domain::id::Id::generate();
    let now = Utc::now();
    let stale = now - Duration::hours(1);
    // 计数与任务实际状态不一致:2 个任务已完成,crawl 仍记 0/0。
    let crawl = Crawl::with_all_fields(
        crawl_id,
        crate::domain::id::Id::generate(),
        "stuck-progress".to_string(),
        "https://example.com/".to_string(),
        "https://example.com/".to_string(),
        CrawlStatus::Queued,
        json!({}),
        2,
        0,
        0,
        stale,
        stale,
        None,
    );
    crawl_repo
        .create(&crawl)
        .await
        .expect("crawl create failed");

    let repo = TaskRepositoryImpl::new(pool.clone(), Duration::minutes(5));
    for _ in 0..2 {
        let mut task = make_test_task_with_unique_url();
        task.crawl_id = Some(crawl_id);
        task.status = TaskStatus::Completed;
        // 任务行也需静默超过 cutoff:刚变更的任务会阻止恢复,防止误终结活跃 crawl。
        task.updated_at = stale;
        repo.create(&task).await.expect("task create failed");
    }

    repo.expire_tasks().await.expect("expire_tasks failed");

    let crawl = crawl_repo
        .find_by_id(crawl_id)
        .await
        .expect("find crawl failed")
        .expect("crawl must exist");
    assert_eq!(crawl.status, CrawlStatus::Completed);
    assert_eq!(crawl.total_tasks(), 2);
    assert_eq!(crawl.completed_tasks(), 2);
    assert_eq!(crawl.failed_tasks(), 0);
    assert!(crawl.completed_at.is_some());
}

/// 恢复对账的反例:最近有任务变更(cutoff 内)时不收口,避免误终结活跃 crawl。
#[tokio::test]
async fn test_expire_tasks_recovers_skips_recent_task_activity() {
    use crate::domain::models::crawl_model::{Crawl, CrawlStatus};
    use crate::domain::repositories::crawl_repository::CrawlRepository;
    use crate::infrastructure::database::repositories::crawl_repo_impl::CrawlRepositoryImpl;

    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let _guard = acquire_next_test_mutex().lock().await;
    let pool = create_test_db_pool();
    let crawl_repo = CrawlRepositoryImpl::new(pool.clone());
    let crawl_id = crate::domain::id::Id::generate();
    let now = Utc::now();
    let stale = now - Duration::hours(1);
    let crawl = Crawl::with_all_fields(
        crawl_id,
        crate::domain::id::Id::generate(),
        "recent-activity".to_string(),
        "https://example.com/".to_string(),
        "https://example.com/".to_string(),
        CrawlStatus::Queued,
        json!({}),
        2,
        0,
        0,
        stale,
        stale,
        None,
    );
    crawl_repo
        .create(&crawl)
        .await
        .expect("crawl create failed");

    let repo = TaskRepositoryImpl::new(pool.clone(), Duration::minutes(5));
    let mut task = make_test_task_with_unique_url();
    task.crawl_id = Some(crawl_id);
    task.status = TaskStatus::Completed;
    // updated_at 为默认 now:属于 cutoff 内的新活动,必须跳过恢复。
    repo.create(&task).await.expect("task create failed");

    repo.expire_tasks().await.expect("expire_tasks failed");

    let crawl = crawl_repo
        .find_by_id(crawl_id)
        .await
        .expect("find crawl failed")
        .expect("crawl must exist");
    assert_eq!(
        crawl.status,
        CrawlStatus::Queued,
        "recent task activity must prevent recovery"
    );
    assert_eq!(crawl.completed_tasks(), 0);
}

/// 恢复对账:声明 total 但零任务行(首任务未插入即崩溃)按全部失败收口。
#[tokio::test]
async fn test_expire_tasks_recovers_crawl_without_task_rows() {
    use crate::domain::models::crawl_model::{Crawl, CrawlStatus};
    use crate::domain::repositories::crawl_repository::CrawlRepository;
    use crate::infrastructure::database::repositories::crawl_repo_impl::CrawlRepositoryImpl;

    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let _guard = acquire_next_test_mutex().lock().await;
    let pool = create_test_db_pool();
    let crawl_repo = CrawlRepositoryImpl::new(pool.clone());
    let crawl_id = crate::domain::id::Id::generate();
    let now = Utc::now();
    let stale = now - Duration::hours(1);
    let crawl = Crawl::with_all_fields(
        crawl_id,
        crate::domain::id::Id::generate(),
        "no-task-rows".to_string(),
        "https://example.com/".to_string(),
        "https://example.com/".to_string(),
        CrawlStatus::Queued,
        json!({}),
        3,
        0,
        0,
        stale,
        stale,
        None,
    );
    crawl_repo
        .create(&crawl)
        .await
        .expect("crawl create failed");

    let repo = TaskRepositoryImpl::new(pool.clone(), Duration::minutes(5));
    repo.expire_tasks().await.expect("expire_tasks failed");

    let crawl = crawl_repo
        .find_by_id(crawl_id)
        .await
        .expect("find crawl failed")
        .expect("crawl must exist");
    assert_eq!(crawl.status, CrawlStatus::Failed);
    assert_eq!(crawl.total_tasks(), 3);
    assert_eq!(crawl.failed_tasks(), 3);
    assert_eq!(crawl.completed_tasks(), 0);
}

#[tokio::test]
async fn test_find_by_crawl_id_with_real_db_returns_empty_for_unknown() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    let result = repo
        .find_by_crawl_id(crate::domain::id::Id::generate())
        .await;
    assert!(
        result.is_ok(),
        "find_by_crawl_id failed: {:?}",
        result.err()
    );
    assert!(
        result.unwrap().is_empty(),
        "unknown crawl_id should return empty vec"
    );
}

#[tokio::test]
async fn test_find_by_crawl_id_with_real_db_returns_matching_tasks() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    let crawl_id = crate::domain::id::Id::generate();
    let mut task1 = make_test_task();
    task1.crawl_id = Some(crawl_id);
    let mut task2 = make_test_task();
    task2.crawl_id = Some(crawl_id);
    task2.url = format!("{}/task2", task2.url);
    let unrelated = make_test_task();
    repo.create(&task1).await.expect("create task1 failed");
    repo.create(&task2).await.expect("create task2 failed");
    repo.create(&unrelated)
        .await
        .expect("create unrelated failed");

    let result = repo.find_by_crawl_id(crawl_id).await;
    assert!(result.is_ok(), "find_by_crawl_id failed");
    let tasks = result.unwrap();
    assert_eq!(tasks.len(), 2, "should find 2 tasks for crawl_id");
    let ids: HashSet<crate::domain::id::Id> = tasks.iter().map(|t| t.id).collect();
    assert!(ids.contains(&task1.id));
    assert!(ids.contains(&task2.id));
    assert!(!ids.contains(&unrelated.id));
}

#[tokio::test]
async fn test_query_tasks_with_real_db_returns_empty_for_unknown_team() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    let params = TaskQueryParams {
        team_id: crate::domain::id::Id::generate(),
        ..Default::default()
    };
    let result = repo.query_tasks(params).await;
    assert!(result.is_ok(), "query_tasks failed: {:?}", result.err());
    let (tasks, total) = result.unwrap();
    assert!(
        tasks.is_empty(),
        "unknown team_id should return empty tasks"
    );
    assert_eq!(total, 0, "unknown team_id should return total=0");
}

#[tokio::test]
async fn test_query_tasks_with_real_db_returns_matching_tasks() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    let team_id = crate::domain::id::Id::generate();
    let mut task1 = make_test_task();
    task1.team_id = team_id;
    task1.task_type = TaskType::Scrape;
    let mut task2 = make_test_task();
    task2.team_id = team_id;
    task2.task_type = TaskType::Crawl;
    repo.create(&task1).await.expect("create task1 failed");
    repo.create(&task2).await.expect("create task2 failed");

    let params = TaskQueryParams {
        team_id,
        limit: 100,
        ..Default::default()
    };
    let result = repo.query_tasks(params).await;
    assert!(result.is_ok(), "query_tasks failed");
    let (tasks, total) = result.unwrap();
    assert_eq!(total, 2, "should find 2 tasks for team_id");
    assert_eq!(tasks.len(), 2);
}

#[tokio::test]
async fn test_batch_cancel_returns_empty_for_empty_input() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    // Empty input should short-circuit to Ok((empty, empty)) without DB access
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    let result = repo
        .batch_cancel(Vec::new(), crate::domain::id::Id::generate(), false)
        .await;
    assert!(result.is_ok());
    let (cancelled, errors) = result.unwrap();
    assert!(cancelled.is_empty());
    assert!(errors.is_empty());
}

#[tokio::test]
async fn test_batch_cancel_with_real_db_returns_errors_for_unknown_ids() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    let unknown_id = crate::domain::id::Id::generate();
    let task_ids = vec![unknown_id];
    let result = repo
        .batch_cancel(task_ids, crate::domain::id::Id::generate(), false)
        .await;
    assert!(
        result.is_ok(),
        "batch_cancel should succeed even with unknown IDs"
    );
    let (cancelled, errors) = result.unwrap();
    assert!(cancelled.is_empty(), "no tasks should be cancelled");
    assert_eq!(errors.len(), 1, "should report 1 error");
    assert_eq!(errors[0].0, unknown_id);
    assert!(errors[0].1.contains("not found"));
}

#[tokio::test]
async fn test_batch_cancel_with_real_db_cancels_owned_tasks() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    let team_id = crate::domain::id::Id::generate();
    let mut task1 = make_test_task();
    task1.team_id = team_id;
    let mut task2 = make_test_task();
    task2.team_id = team_id;
    repo.create(&task1).await.expect("create task1 failed");
    repo.create(&task2).await.expect("create task2 failed");

    let result = repo
        .batch_cancel(vec![task1.id, task2.id], team_id, false)
        .await;
    assert!(result.is_ok(), "batch_cancel failed");
    let (cancelled, errors) = result.unwrap();
    assert_eq!(cancelled.len(), 2, "both tasks should be cancelled");
    assert!(errors.is_empty(), "no errors expected");

    let found1 = repo
        .find_by_id(task1.id)
        .await
        .expect("find_by_id failed")
        .expect("task1 should exist");
    assert_eq!(found1.status, TaskStatus::Cancelled);
    assert!(
        found1.completed_at.is_some(),
        "cancelled 行必须写 completed_at"
    );
    assert!(found1.lock_token.is_none(), "cancelled 行必须清锁");
    assert!(
        found1.lock_expires_at.is_none(),
        "cancelled 行必须清锁过期时间"
    );
    let found2 = repo
        .find_by_id(task2.id)
        .await
        .expect("find_by_id failed")
        .expect("task2 should exist");
    assert_eq!(found2.status, TaskStatus::Cancelled);
}

// RepositoryError variant tests

#[test]
fn test_error_database_display() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let err = RepositoryError::Database(anyhow::anyhow!("conn refused"));
    assert!(err.to_string().contains("Database error"));
    assert!(err.to_string().contains("conn refused"));
}

#[test]
fn test_error_not_found_display() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let err = RepositoryError::NotFound;
    assert!(err.to_string().contains("Record not found"));
}

#[test]
fn test_from_dberr_to_repository_error() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let db_err = dbnexus::sea_orm::DbErr::Custom("query failed".to_string());
    let repo_err: RepositoryError = db_err.into();
    assert!(matches!(repo_err, RepositoryError::Database(_)));
    assert!(repo_err.to_string().contains("query failed"));
}

// Additional construction & accessor tests

#[test]
fn test_pool_accessor_returns_reference_to_same_pool() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let pool = create_test_db_pool();
    let repo = TaskRepositoryImpl::new(pool.clone(), Duration::minutes(5));
    let pool_ref = repo.pool();
    // The accessor should return a reference to the same underlying Arc
    assert!(Arc::ptr_eq(pool_ref, &pool));
}

#[test]
fn test_new_with_zero_lock_duration() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let pool = create_test_db_pool();
    let repo = TaskRepositoryImpl::new(pool, Duration::zero());
    let _ = repo;
}

#[test]
fn test_new_with_large_lock_duration() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let pool = create_test_db_pool();
    let repo = TaskRepositoryImpl::new(pool, Duration::days(7));
    let _ = repo;
}

#[test]
fn test_make_test_task_construction() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let task = make_test_task();
    assert_eq!(task.task_type, TaskType::Scrape);
    assert_eq!(task.url, "http://example.com");
    // New tasks should be in Queued status
    assert_eq!(task.status, TaskStatus::Queued);
}

#[test]
fn test_task_query_params_default() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let params = TaskQueryParams::default();
    // Default should have nil crate::domain::id::Id for team_id
    assert_eq!(params.team_id, crate::domain::id::Id::nil());
    assert!(params.crawl_id.is_none());
    assert!(params.statuses.is_none());
    assert!(params.task_types.is_none());
    assert_eq!(params.limit, 0);
    assert_eq!(params.offset, 0);
}

// query_tasks — exercise optional filter branches.
// Each test verifies that filter combinations are accepted and
// return Ok with an empty result set against a fresh team_id.

#[tokio::test]
async fn test_query_tasks_with_crawl_id_returns_empty() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    let params = TaskQueryParams {
        team_id: crate::domain::id::Id::generate(),
        crawl_id: Some(crate::domain::id::Id::generate()),
        ..Default::default()
    };
    let result = repo.query_tasks(params).await;
    assert!(result.is_ok(), "query_tasks failed: {:?}", result.err());
    let (tasks, total) = result.unwrap();
    assert!(tasks.is_empty());
    assert_eq!(total, 0);
}

#[tokio::test]
async fn test_query_tasks_with_statuses_returns_empty() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    let params = TaskQueryParams {
        team_id: crate::domain::id::Id::generate(),
        statuses: Some(vec![TaskStatus::Queued, TaskStatus::Active]),
        ..Default::default()
    };
    let result = repo.query_tasks(params).await;
    assert!(result.is_ok(), "query_tasks failed: {:?}", result.err());
    let (tasks, total) = result.unwrap();
    assert!(tasks.is_empty());
    assert_eq!(total, 0);
}

#[tokio::test]
async fn test_query_tasks_with_task_types_returns_empty() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    let params = TaskQueryParams {
        team_id: crate::domain::id::Id::generate(),
        task_types: Some(vec![TaskType::Scrape, TaskType::Crawl, TaskType::Extract]),
        ..Default::default()
    };
    let result = repo.query_tasks(params).await;
    assert!(result.is_ok(), "query_tasks failed: {:?}", result.err());
    let (tasks, total) = result.unwrap();
    assert!(tasks.is_empty());
    assert_eq!(total, 0);
}

#[tokio::test]
async fn test_query_tasks_with_all_optional_filters_returns_empty() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    let params = TaskQueryParams {
        team_id: crate::domain::id::Id::generate(),
        crawl_id: Some(crate::domain::id::Id::generate()),
        statuses: Some(vec![TaskStatus::Completed, TaskStatus::Failed]),
        task_types: Some(vec![TaskType::Scrape]),
        limit: 50,
        offset: 10,
        ..Default::default()
    };
    let result = repo.query_tasks(params).await;
    assert!(result.is_ok(), "query_tasks failed: {:?}", result.err());
    let (tasks, total) = result.unwrap();
    assert!(tasks.is_empty());
    assert_eq!(total, 0);
}

// Additional boundary tests for existing methods

#[tokio::test]
async fn test_find_existing_urls_with_multiple_urls_returns_empty_for_unknown() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    let urls = vec![
        format!(
            "http://nonexistent-{}.com",
            crate::domain::id::Id::generate()
        ),
        format!(
            "http://nonexistent-{}.com",
            crate::domain::id::Id::generate()
        ),
        format!(
            "http://nonexistent-{}.com",
            crate::domain::id::Id::generate()
        ),
    ];
    let result = repo.find_existing_urls(&urls).await;
    assert!(result.is_ok(), "find_existing_urls failed");
    assert!(result.unwrap().is_empty());
}

#[tokio::test]
async fn test_batch_cancel_with_multiple_ids_returns_errors_for_unknown() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    let id1 = crate::domain::id::Id::generate();
    let id2 = crate::domain::id::Id::generate();
    let id3 = crate::domain::id::Id::generate();
    let task_ids = vec![id1, id2, id3];
    let result = repo
        .batch_cancel(task_ids, crate::domain::id::Id::generate(), false)
        .await;
    assert!(result.is_ok(), "batch_cancel should succeed");
    let (cancelled, errors) = result.unwrap();
    assert!(cancelled.is_empty());
    assert_eq!(errors.len(), 3, "all 3 IDs should be reported as not found");
    let error_ids: HashSet<crate::domain::id::Id> = errors.iter().map(|(id, _)| *id).collect();
    assert!(error_ids.contains(&id1));
    assert!(error_ids.contains(&id2));
    assert!(error_ids.contains(&id3));
}

#[tokio::test]
async fn test_batch_cancel_with_force_true_returns_errors_for_unknown() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    let task_ids = vec![crate::domain::id::Id::generate()];
    let result = repo
        .batch_cancel(task_ids, crate::domain::id::Id::generate(), true)
        .await;
    assert!(result.is_ok(), "batch_cancel should succeed");
    let (cancelled, errors) = result.unwrap();
    assert!(cancelled.is_empty());
    assert_eq!(errors.len(), 1);
}

#[tokio::test]
async fn test_reset_stuck_tasks_with_zero_duration_returns_zero_or_more() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    let result = repo.reset_stuck_tasks(Duration::zero()).await;
    assert!(
        result.is_ok(),
        "reset_stuck_tasks failed: {:?}",
        result.err()
    );
    // Zero duration means cutoff is now; only tasks started in the past
    // would be affected, which is none for a fresh task. Returns Ok(count).
    let _count = result.unwrap();
}

#[tokio::test]
async fn test_reset_stuck_tasks_with_negative_duration_returns_zero_or_more() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    // Negative duration means cutoff is in the future; no tasks should
    // have started_at past a future cutoff.
    let result = repo.reset_stuck_tasks(Duration::minutes(-30)).await;
    assert!(
        result.is_ok(),
        "reset_stuck_tasks failed: {:?}",
        result.err()
    );
    let _count = result.unwrap();
}

#[tokio::test]
async fn test_exists_by_url_with_empty_string_returns_false() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    let result = repo.exists_by_url("").await;
    assert!(result.is_ok(), "exists_by_url failed: {:?}", result.err());
    // Empty string is unlikely to match any task URL.
    let _exists = result.unwrap();
}

// Additional From<dbnexus::sea_orm::DbErr> variant coverage

#[test]
fn test_from_dberr_record_not_found_to_repository_error() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let db_err = dbnexus::sea_orm::DbErr::RecordNotFound("task missing".to_string());
    let repo_err: RepositoryError = db_err.into();
    assert!(matches!(repo_err, RepositoryError::Database(_)));
    assert!(repo_err.to_string().contains("task missing"));
}

#[test]
fn test_from_dberr_connection_acquire_to_repository_error() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let db_err =
        dbnexus::sea_orm::DbErr::ConnectionAcquire(dbnexus::sea_orm::ConnAcquireErr::Timeout);
    let repo_err: RepositoryError = db_err.into();
    assert!(matches!(repo_err, RepositoryError::Database(_)));
}

#[test]
fn test_from_dberr_record_not_inserted_to_repository_error() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let db_err = dbnexus::sea_orm::DbErr::RecordNotInserted;
    let repo_err: RepositoryError = db_err.into();
    assert!(matches!(repo_err, RepositoryError::Database(_)));
}

#[test]
fn test_from_dberr_query_runtime_to_repository_error() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let db_err = dbnexus::sea_orm::DbErr::Query(dbnexus::sea_orm::RuntimeErr::Internal(
        "syntax error".to_string(),
    ));
    let repo_err: RepositoryError = db_err.into();
    assert!(matches!(repo_err, RepositoryError::Database(_)));
    assert!(repo_err.to_string().contains("syntax error"));
}

// TaskType / TaskStatus display exhaustive

#[test]
fn test_task_type_scrape_display() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    assert_eq!(format!("{}", TaskType::Scrape), "scrape");
}

#[test]
fn test_task_type_crawl_display() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    assert_eq!(format!("{}", TaskType::Crawl), "crawl");
}

#[test]
fn test_task_type_extract_display() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    assert_eq!(format!("{}", TaskType::Extract), "extract");
}

#[test]
fn test_task_status_queued_display() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    assert_eq!(format!("{}", TaskStatus::Queued), "queued");
}

#[test]
fn test_task_status_active_display() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    assert_eq!(format!("{}", TaskStatus::Active), "active");
}

#[test]
fn test_task_status_completed_display() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    assert_eq!(format!("{}", TaskStatus::Completed), "completed");
}

#[test]
fn test_task_status_failed_display() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    assert_eq!(format!("{}", TaskStatus::Failed), "failed");
}

#[test]
fn test_task_status_cancelled_display() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    assert_eq!(format!("{}", TaskStatus::Cancelled), "cancelled");
}

// Additional From<dbnexus::sea_orm::DbErr> variant coverage (exhaustive)
// 覆盖 dbnexus::sea_orm::DbErr 所有未在前面测试的变体到 RepositoryError::Database 的转换

#[test]
fn test_from_dberr_connection_acquire_closed_to_repository_error() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let db_err = dbnexus::sea_orm::DbErr::ConnectionAcquire(
        dbnexus::sea_orm::ConnAcquireErr::ConnectionClosed,
    );
    let repo_err: RepositoryError = db_err.into();
    assert!(matches!(repo_err, RepositoryError::Database(_)));
}

#[test]
fn test_from_dberr_record_not_updated_to_repository_error() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let db_err = dbnexus::sea_orm::DbErr::RecordNotUpdated;
    let repo_err: RepositoryError = db_err.into();
    assert!(matches!(repo_err, RepositoryError::Database(_)));
}

#[test]
fn test_from_dberr_query_sqlx_error_to_repository_error() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let inner = dbnexus::sea_orm::sqlx::Error::RowNotFound;
    let db_err = dbnexus::sea_orm::DbErr::Query(dbnexus::sea_orm::RuntimeErr::SqlxError(
        std::sync::Arc::new(inner),
    ));
    let repo_err: RepositoryError = db_err.into();
    assert!(matches!(repo_err, RepositoryError::Database(_)));
}

#[test]
fn test_from_dberr_conn_runtime_to_repository_error() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let db_err = dbnexus::sea_orm::DbErr::Conn(dbnexus::sea_orm::RuntimeErr::Internal(
        "conn lost".to_string(),
    ));
    let repo_err: RepositoryError = db_err.into();
    assert!(matches!(repo_err, RepositoryError::Database(_)));
    assert!(repo_err.to_string().contains("conn lost"));
}

#[test]
fn test_from_dberr_exec_runtime_to_repository_error() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let db_err = dbnexus::sea_orm::DbErr::Exec(dbnexus::sea_orm::RuntimeErr::Internal(
        "exec failed".to_string(),
    ));
    let repo_err: RepositoryError = db_err.into();
    assert!(matches!(repo_err, RepositoryError::Database(_)));
    assert!(repo_err.to_string().contains("exec failed"));
}

#[test]
fn test_from_dberr_type_to_repository_error() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let db_err = dbnexus::sea_orm::DbErr::Type("invalid type".to_string());
    let repo_err: RepositoryError = db_err.into();
    assert!(matches!(repo_err, RepositoryError::Database(_)));
    assert!(repo_err.to_string().contains("invalid type"));
}

#[test]
fn test_from_dberr_json_to_repository_error() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let db_err = dbnexus::sea_orm::DbErr::Json("parse error".to_string());
    let repo_err: RepositoryError = db_err.into();
    assert!(matches!(repo_err, RepositoryError::Database(_)));
    assert!(repo_err.to_string().contains("parse error"));
}

#[test]
fn test_from_dberr_attr_not_set_to_repository_error() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let db_err = dbnexus::sea_orm::DbErr::AttrNotSet("name".to_string());
    let repo_err: RepositoryError = db_err.into();
    assert!(matches!(repo_err, RepositoryError::Database(_)));
    assert!(repo_err.to_string().contains("name"));
}

#[test]
fn test_from_dberr_convert_from_u64_to_repository_error() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let db_err = dbnexus::sea_orm::DbErr::ConvertFromU64("String");
    let repo_err: RepositoryError = db_err.into();
    assert!(matches!(repo_err, RepositoryError::Database(_)));
}

#[test]
fn test_from_dberr_unpack_insert_id_to_repository_error() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let db_err = dbnexus::sea_orm::DbErr::UnpackInsertId;
    let repo_err: RepositoryError = db_err.into();
    assert!(matches!(repo_err, RepositoryError::Database(_)));
}

#[test]
fn test_from_dberr_update_get_primary_key_to_repository_error() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let db_err = dbnexus::sea_orm::DbErr::UpdateGetPrimaryKey;
    let repo_err: RepositoryError = db_err.into();
    assert!(matches!(repo_err, RepositoryError::Database(_)));
}

#[test]
fn test_from_dberr_migration_to_repository_error() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let db_err = dbnexus::sea_orm::DbErr::Migration("schema mismatch".to_string());
    let repo_err: RepositoryError = db_err.into();
    assert!(matches!(repo_err, RepositoryError::Database(_)));
    assert!(repo_err.to_string().contains("schema mismatch"));
}

#[test]
fn test_from_dberr_mutex_poison_error_to_repository_error() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let db_err = dbnexus::sea_orm::DbErr::MutexPoisonError;
    let repo_err: RepositoryError = db_err.into();
    assert!(matches!(repo_err, RepositoryError::Database(_)));
}

#[test]
fn test_from_dberr_rbac_error_to_repository_error() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let db_err = dbnexus::sea_orm::DbErr::RbacError("forbidden".to_string());
    let repo_err: RepositoryError = db_err.into();
    assert!(matches!(repo_err, RepositoryError::Database(_)));
    assert!(repo_err.to_string().contains("forbidden"));
}

#[test]
fn test_from_dberr_access_denied_to_repository_error() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let db_err = dbnexus::sea_orm::DbErr::AccessDenied {
        permission: "write".to_string(),
        resource: "task".to_string(),
    };
    let repo_err: RepositoryError = db_err.into();
    assert!(matches!(repo_err, RepositoryError::Database(_)));
    assert!(repo_err.to_string().contains("write"));
    assert!(repo_err.to_string().contains("task"));
}

#[test]
fn test_from_dberr_backend_not_supported_to_repository_error() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let db_err = dbnexus::sea_orm::DbErr::BackendNotSupported {
        db: "mysql",
        ctx: "not configured",
    };
    let repo_err: RepositoryError = db_err.into();
    assert!(matches!(repo_err, RepositoryError::Database(_)));
}

#[test]
fn test_from_dberr_try_into_err_to_repository_error() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let source_err: std::sync::Arc<dyn std::error::Error + Send + Sync> = std::sync::Arc::new(
        std::io::Error::new(std::io::ErrorKind::InvalidData, "bad value"),
    );
    let db_err = dbnexus::sea_orm::DbErr::TryIntoErr {
        from: "String",
        into: "i32",
        source: source_err,
    };
    let repo_err: RepositoryError = db_err.into();
    assert!(matches!(repo_err, RepositoryError::Database(_)));
}

#[test]
fn test_from_dberr_key_arity_mismatch_to_repository_error() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let db_err = dbnexus::sea_orm::DbErr::KeyArityMismatch {
        expected: 2,
        received: 1,
    };
    let repo_err: RepositoryError = db_err.into();
    assert!(matches!(repo_err, RepositoryError::Database(_)));
}

#[test]
fn test_from_dberr_primary_key_not_set_to_repository_error() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let db_err = dbnexus::sea_orm::DbErr::PrimaryKeyNotSet { ctx: "update" };
    let repo_err: RepositoryError = db_err.into();
    assert!(matches!(repo_err, RepositoryError::Database(_)));
}

// RepositoryError Display — 精确消息内容验证

#[test]
fn test_repository_error_database_display_exact() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let err = RepositoryError::Database(anyhow::anyhow!("connection refused"));
    let msg = err.to_string();
    assert!(msg.contains("Database error"));
    assert!(msg.contains("connection refused"));
}

#[test]
fn test_repository_error_database_display_with_empty_message() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let err = RepositoryError::Database(anyhow::anyhow!(""));
    let msg = err.to_string();
    assert!(msg.contains("Database error"));
}

#[test]
fn test_repository_error_not_found_display_exact() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let err = RepositoryError::NotFound;
    assert_eq!(err.to_string(), "Record not found");
}

#[test]
fn test_repository_error_implements_debug() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let err1 = RepositoryError::Database(anyhow::anyhow!("e"));
    let err2 = RepositoryError::NotFound;
    let debug1 = format!("{:?}", err1);
    let debug2 = format!("{:?}", err2);
    assert!(!debug1.is_empty());
    assert!(!debug2.is_empty());
}

// Additional boundary tests for URL-based methods

#[tokio::test]
async fn test_exists_by_url_with_unicode_returns_false_for_unknown() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    let result = repo.exists_by_url("http://例子.com/测试").await;
    assert!(result.is_ok(), "exists_by_url failed: {:?}", result.err());
    let _exists = result.unwrap();
}

#[tokio::test]
async fn test_exists_by_url_with_long_url_returns_false_for_unknown() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    let long_url = format!(
        "http://nonexistent-{}.com/{}",
        crate::domain::id::Id::generate(),
        "a".repeat(2000)
    );
    let result = repo.exists_by_url(&long_url).await;
    assert!(result.is_ok(), "exists_by_url failed: {:?}", result.err());
    assert!(!result.unwrap(), "long unknown URL should return false");
}

#[tokio::test]
async fn test_find_existing_urls_with_unicode_urls_returns_empty_for_unknown() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    let urls = vec![
        format!("http://例子-{}.com", crate::domain::id::Id::generate()),
        format!("http://example-{}.org", crate::domain::id::Id::generate()),
    ];
    let result = repo.find_existing_urls(&urls).await;
    assert!(result.is_ok(), "find_existing_urls failed");
    assert!(result.unwrap().is_empty());
}

#[tokio::test]
async fn test_find_existing_urls_with_empty_string_in_list_returns_empty() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    let urls = vec!["".to_string()];
    let result = repo.find_existing_urls(&urls).await;
    assert!(result.is_ok(), "find_existing_urls failed");
    // Empty string is unlikely to match any task URL.
    let _existing = result.unwrap();
}

#[tokio::test]
async fn test_find_existing_urls_with_mixed_empty_and_nonempty_returns_only_matches() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    let task = make_test_task_with_unique_url();
    repo.create(&task).await.expect("create failed");
    let urls = vec!["".to_string(), task.url.clone()];
    let result = repo.find_existing_urls(&urls).await;
    assert!(result.is_ok(), "find_existing_urls failed");
    let existing = result.unwrap();
    assert!(
        existing.contains(&task.url),
        "should find the created task URL"
    );
}

// Additional boundary tests for UUID-based methods

#[tokio::test]
async fn test_find_by_id_with_nil_uuid_returns_none() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    let result = repo.find_by_id(crate::domain::id::Id::nil()).await;
    assert!(result.is_ok(), "find_by_id failed: {:?}", result.err());
    // Nil UUID is unlikely to match any task (we generate v4 UUIDs in tests).
    let _found = result.unwrap();
}

#[tokio::test]
async fn test_mark_completed_with_nil_uuid_succeeds_silently() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    // (this is the current implementation behavior).
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    let result = repo
        .mark_completed(crate::domain::id::Id::nil(), None)
        .await;
    assert!(result.is_ok(), "mark_completed failed: {:?}", result.err());
}

#[tokio::test]
async fn test_mark_failed_with_nil_uuid_succeeds_silently() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    let result = repo.mark_failed(crate::domain::id::Id::nil(), None).await;
    assert!(result.is_ok(), "mark_failed failed: {:?}", result.err());
}

#[tokio::test]
async fn test_mark_cancelled_with_nil_uuid_succeeds_silently() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    let result = repo.mark_cancelled(crate::domain::id::Id::nil()).await;
    assert!(result.is_ok(), "mark_cancelled failed: {:?}", result.err());
}

#[tokio::test]
async fn test_acquire_next_with_nil_worker_id_returns_ok() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    // 序列化 acquire_next 测试:防止并行测试间相互获取 task
    let _guard = acquire_next_test_mutex().lock().await;
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    let result = repo.acquire_next(crate::domain::id::Id::nil()).await;
    assert!(result.is_ok(), "acquire_next failed: {:?}", result.err());
    // Whether Some or None depends on the backlog; we just verify Ok.
    let _acquired = result.unwrap();
}

#[tokio::test]
async fn test_cancel_tasks_by_crawl_id_with_nil_uuid_returns_zero() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    let result = repo
        .cancel_tasks_by_crawl_id(crate::domain::id::Id::nil())
        .await;
    assert!(
        result.is_ok(),
        "cancel_tasks_by_crawl_id failed: {:?}",
        result.err()
    );
    // Nil UUID is unlikely to match any task's crawl_id (most are None or set to v4).
    let _count = result.unwrap();
}

#[tokio::test]
async fn test_find_by_crawl_id_with_nil_uuid_returns_empty() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    let result = repo.find_by_crawl_id(crate::domain::id::Id::nil()).await;
    assert!(
        result.is_ok(),
        "find_by_crawl_id failed: {:?}",
        result.err()
    );
    // Nil UUID is unlikely to match any task's crawl_id.
    let _tasks = result.unwrap();
}

#[tokio::test]
async fn test_batch_cancel_with_nil_uuids_returns_errors() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    let task_ids = vec![crate::domain::id::Id::nil()];
    let result = repo
        .batch_cancel(task_ids, crate::domain::id::Id::nil(), false)
        .await;
    assert!(result.is_ok(), "batch_cancel should succeed");
    let (cancelled, errors) = result.unwrap();
    assert!(
        cancelled.is_empty(),
        "nil UUID task should not be cancelled"
    );
    assert_eq!(
        errors.len(),
        1,
        "nil UUID task should be reported as not found"
    );
}

// query_tasks boundary — extreme limit/offset values

#[tokio::test]
async fn test_query_tasks_with_zero_limit_offset_returns_empty() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    let params = TaskQueryParams {
        team_id: crate::domain::id::Id::generate(),
        limit: 0,
        offset: 0,
        ..Default::default()
    };
    let result = repo.query_tasks(params).await;
    assert!(result.is_ok(), "query_tasks failed: {:?}", result.err());
    let (tasks, total) = result.unwrap();
    assert!(tasks.is_empty());
    assert_eq!(total, 0);
}

#[tokio::test]
async fn test_query_tasks_with_max_limit_returns_empty() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    let params = TaskQueryParams {
        team_id: crate::domain::id::Id::generate(),
        limit: u32::MAX,
        offset: 0,
        ..Default::default()
    };
    let result = repo.query_tasks(params).await;
    assert!(result.is_ok(), "query_tasks failed: {:?}", result.err());
    let (tasks, total) = result.unwrap();
    assert!(tasks.is_empty());
    assert_eq!(total, 0);
}

#[tokio::test]
async fn test_query_tasks_with_nil_team_id_returns_empty() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    let params = TaskQueryParams {
        team_id: crate::domain::id::Id::nil(),
        ..Default::default()
    };
    let result = repo.query_tasks(params).await;
    assert!(result.is_ok(), "query_tasks failed: {:?}", result.err());
    // Nil team_id is unlikely to match any task (we use v4 UUIDs).
    let (tasks, _total) = result.unwrap();
    assert!(tasks.is_empty());
}

#[tokio::test]
async fn test_query_tasks_with_empty_statuses_vec_returns_empty() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    let params = TaskQueryParams {
        team_id: crate::domain::id::Id::generate(),
        statuses: Some(Vec::new()),
        ..Default::default()
    };
    let result = repo.query_tasks(params).await;
    assert!(result.is_ok(), "query_tasks failed: {:?}", result.err());
    let (tasks, total) = result.unwrap();
    assert!(tasks.is_empty());
    assert_eq!(total, 0);
}

#[tokio::test]
async fn test_query_tasks_with_empty_task_types_vec_returns_empty() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let repo = TaskRepositoryImpl::new(create_test_db_pool(), Duration::minutes(5));
    let params = TaskQueryParams {
        team_id: crate::domain::id::Id::generate(),
        task_types: Some(Vec::new()),
        ..Default::default()
    };
    let result = repo.query_tasks(params).await;
    assert!(result.is_ok(), "query_tasks failed: {:?}", result.err());
    let (tasks, total) = result.unwrap();
    assert!(tasks.is_empty());
    assert_eq!(total, 0);
}

// Repository clone — verify Clone preserves pool identity

#[test]
fn test_repository_clone_preserves_pool_identity() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    let pool = create_test_db_pool();
    let repo = TaskRepositoryImpl::new(pool.clone(), Duration::minutes(5));
    let cloned = repo.clone();
    assert!(Arc::ptr_eq(&repo.pool, &cloned.pool));
}

#[test]
fn test_new_with_distinct_pools_do_not_share_identity() {
    if crate::common::test_helpers::skip_if_no_test_db() {
        return;
    }
    // create_test_db_pool 是进程级共享单池(连接数 O(1) test_helpers),
    // 独立池身份需用 build_independent_test_db_pool 直接构造两个 DbPool 验证。
    let pool1 = crate::common::test_helpers::build_independent_test_db_pool();
    let pool2 = crate::common::test_helpers::build_independent_test_db_pool();
    let repo1 = TaskRepositoryImpl::new(pool1, Duration::minutes(5));
    let repo2 = TaskRepositoryImpl::new(pool2, Duration::minutes(5));
    assert!(!Arc::ptr_eq(&repo1.pool, &repo2.pool));
}