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
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
// Copyright (c) 2025-2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

use axum::{
    extract::{Extension, Json},
    http::StatusCode,
    response::IntoResponse,
};
use log::error;
use std::sync::Arc;

use crate::{
    application::dto::search_request::{SearchRequestDto, SearchResponseDto, SearchResultDto},
    common::constants::crawl_task,
    domain::{
        repositories::task_repository::TaskRepository,
        services::rate_limiting_service::RateLimitingService,
        services::search_service::{
            SearchQuery, SearchResponse, SearchServiceError, SearchServiceTrait,
        },
    },
    i18n::{I18nBundle, Locale},
    presentation::handlers::check_ssrf_url,
    presentation::handlers::response_builder::{
        error_response, json_rejection_response, success_response,
    },
    presentation::handlers::task_queries::wait_for_tasks_completion,
    presentation::helpers::rate_limit_helper::check_rate_limit,
    presentation::middleware::auth_middleware::AuthState,
};

/// 处理搜索请求
#[allow(clippy::too_many_arguments)] // axum Extension 提取器:每个依赖独立参数
pub async fn search(
    Extension(search_service): Extension<Arc<dyn SearchServiceTrait>>,
    Extension(task_repo): Extension<Arc<dyn TaskRepository>>,
    Extension(rate_limiting_service): Extension<Arc<dyn RateLimitingService>>,
    Extension(geo_restriction_repo): Extension<
        Option<
            Arc<
                dyn crate::domain::repositories::geo_restriction_repository::GeoRestrictionRepository,
            >,
        >,
    >,
    Extension(auth_state): Extension<AuthState>,
    Extension(locale): Extension<Locale>,
    Extension(bundle): Extension<Arc<I18nBundle>>,
    payload: Result<Json<SearchRequestDto>, axum::extract::rejection::JsonRejection>,
) -> impl IntoResponse {
    // 提取器级拒绝(非法 JSON / 字段缺失)映射为统一包封,避免纯文本响应
    let Json(payload) = match payload {
        Ok(parsed) => parsed,
        Err(ref rej) => return json_rejection_response(rej),
    };
    let team_id = auth_state.team_id;
    let api_key_id = auth_state.api_key_id;

    // 1. 检查限流
    // 性能直接传 `crate::domain::id::Id`(实现 Display),由 helper 内部按需 to_string,
    // 消除 handler 中的中间变量分配。
    if let Err(response) =
        check_rate_limit(rate_limiting_service.as_ref(), api_key_id, "/v1/search").await
    {
        return response;
    }

    // 2. 检查配额 (SearchService 内部已经处理了配额检查)

    let sync_wait_ms = payload
        .sync_wait_ms
        .unwrap_or(crawl_task::DEFAULT_TIMEOUT_MS as u32);

    // 将 DTO 转换为领域参数;派生 crawl 必须携带团队当前黑名单,
    // 否则执行期复核(worker)对搜索结果抓取失效。
    let mut search_query = into_search_query(payload);
    // crawl_results=true 时即使请求省略 crawl_config 也要派生默认配置:
    // 否则派生任务拿不到团队黑名单(策略随“可选字段未传”失效)。
    if search_query.crawl_results == Some(true) {
        let config = search_query.crawl_config.get_or_insert_with(
            crate::domain::services::search_service::SearchCrawlConfig::default,
        );
        // 与 HTTP 创建入口同口径:拒绝超深派生 crawl,避免绕过深度上限。
        if config.max_depth > crate::domain::services::search_service::MAX_SEARCH_CRAWL_DEPTH {
            return error_response(
                StatusCode::BAD_REQUEST,
                format!(
                    "crawl_config.max_depth must be <= {}",
                    crate::domain::services::search_service::MAX_SEARCH_CRAWL_DEPTH
                ),
            );
        }
        if let Some(repo) = geo_restriction_repo.as_ref() {
            match repo.get_team_restrictions(team_id).await {
                Ok(restrictions) => match restrictions.effective_domain_blacklist() {
                    Ok(list) => config.domain_blacklist = list,
                    Err(message) => {
                        error!("Invalid team domain blacklist: {}", message);
                        return error_response(StatusCode::BAD_REQUEST, &message);
                    }
                },
                Err(e) => {
                    error!("Failed to load geo restrictions for search crawl: {}", e);
                    return error_response(
                        StatusCode::INTERNAL_SERVER_ERROR,
                        "Internal server error",
                    );
                }
            }
        }
    }

    // SSRF 防护 (CWE-918):验证 crawl_config.proxy 不指向内部网络
    if let Some(response) = check_search_proxy_ssrf(&search_query, team_id, api_key_id).await {
        return response;
    }

    // 使用注入的SearchService
    match execute_search(
        search_service.as_ref(),
        task_repo.as_ref(),
        team_id,
        api_key_id,
        search_query,
        sync_wait_ms,
    )
    .await
    {
        Ok(response_dto) => success_response(StatusCode::OK, response_dto),
        Err(e) => search_error_response(e, &locale, &bundle),
    }
}

/// 执行搜索;启用爬取结果且有 crawl_id 时等待子任务完成,返回 DTO。
async fn execute_search(
    search_service: &dyn SearchServiceTrait,
    task_repo: &dyn TaskRepository,
    team_id: crate::domain::id::Id,
    api_key_id: crate::domain::id::Id,
    search_query: SearchQuery,
    sync_wait_ms: u32,
) -> Result<SearchResponseDto, SearchServiceError> {
    let response = search_service
        .search(team_id, api_key_id, search_query)
        .await?;

    // 如果启用了爬取结果并且有crawl_id,则等待任务完成
    await_search_crawl_tasks(task_repo, response.crawl_id, team_id, sync_wait_ms).await;

    // 将领域响应转换为 DTO
    Ok(into_search_response_dto(response))
}

/// 将搜索请求 DTO 转换为领域查询参数。
fn into_search_query(payload: SearchRequestDto) -> SearchQuery {
    SearchQuery {
        query: payload.query,
        limit: payload.limit,
        lang: payload.lang,
        country: payload.country,
        engine: payload.engine,
        sources: payload.sources,
        crawl_results: payload.crawl_results,
        crawl_config: payload.crawl_config.map(|c| {
            crate::domain::services::search_service::SearchCrawlConfig {
                max_depth: c.max_depth,
                include_patterns: c.include_patterns,
                exclude_patterns: c.exclude_patterns,
                strategy: c.strategy.unwrap_or_else(|| "bfs".to_string()),
                crawl_delay_ms: c.crawl_delay_ms,
                max_concurrency: c.max_concurrency.unwrap_or(10),
                headers: c.headers,
                proxy: c.proxy,
                extraction_rules: c.extraction_rules,
                domain_blacklist: Vec::new(),
            }
        }),
    }
}

/// SSRF 防护 (CWE-918):验证 crawl_config.proxy 不指向内部网络。
async fn check_search_proxy_ssrf(
    search_query: &SearchQuery,
    team_id: crate::domain::id::Id,
    api_key_id: crate::domain::id::Id,
) -> Option<axum::response::Response> {
    if let Some(ref config) = search_query.crawl_config {
        if let Some(ref proxy_url) = config.proxy {
            if let Some(response) = check_ssrf_url(proxy_url, team_id, api_key_id).await {
                return Some(response);
            }
        }
    }
    None
}

/// 如果启用了爬取结果并且有 crawl_id,则等待任务完成。
async fn await_search_crawl_tasks(
    task_repo: &dyn TaskRepository,
    crawl_id: Option<crate::domain::id::Id>,
    team_id: crate::domain::id::Id,
    sync_wait_ms: u32,
) {
    if sync_wait_ms == 0 {
        return;
    }
    let Some(crawl_id) = crawl_id else {
        return;
    };

    match task_repo.find_by_crawl_id(crawl_id).await {
        Ok(tasks) => {
            if !tasks.is_empty() {
                let task_ids: Vec<crate::domain::id::Id> =
                    tasks.iter().map(|task| task.id).collect();
                match wait_for_tasks_completion(
                    task_repo,
                    &task_ids,
                    team_id,
                    sync_wait_ms,
                    crawl_task::BASE_POLL_INTERVAL_MS,
                )
                .await
                {
                    Ok(_) => {
                        // 等待成功,可以返回响应
                    }
                    Err(e) => {
                        error!("Failed to wait for task completion: {:?}", e);
                    }
                }
            }
        }
        Err(e) => {
            error!("Failed to find tasks for crawl {}: {:?}", crawl_id, e);
        }
    }
}

/// 将领域搜索响应转换为 DTO。
fn into_search_response_dto(response: SearchResponse) -> SearchResponseDto {
    SearchResponseDto {
        query: response.query,
        results: response
            .results
            .into_iter()
            .map(|r| SearchResultDto {
                title: r.title,
                url: r.url,
                description: r.description,
                engine: Some(r.engine),
                score: r.score,
            })
            .collect(),
        crawl_id: response.crawl_id,
        credits_used: response.credits_used,
    }
}

/// 将搜索服务错误映射为统一错误响应。
fn search_error_response(
    e: SearchServiceError,
    locale: &Locale,
    bundle: &Arc<I18nBundle>,
) -> axum::response::Response {
    match e {
        SearchServiceError::UnknownEngine(name) => {
            let msg = crate::i18n::t_with_args(
                locale,
                bundle,
                "search-error-unknown-engine",
                &[("name", name.as_str().to_string())],
            );
            error_response(StatusCode::BAD_REQUEST, msg)
        }
        SearchServiceError::SmartSearchFailed(detail) => {
            let msg = crate::i18n::t_with_args(
                locale,
                bundle,
                "search-error-smart-search",
                &[("message", detail.as_str().to_string())],
            );
            error_response(StatusCode::INTERNAL_SERVER_ERROR, msg)
        }
        other => {
            let (status, msg): (StatusCode, String) = other.into();
            error_response(status, msg)
        }
    }
}

impl From<SearchServiceError> for (StatusCode, String) {
    fn from(err: SearchServiceError) -> Self {
        match err {
            SearchServiceError::ValidationError(details) => (StatusCode::BAD_REQUEST, details),
            SearchServiceError::Repository(e) => (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
            SearchServiceError::CreditsRepository(e) => {
                (StatusCode::INTERNAL_SERVER_ERROR, e.to_string())
            }
            SearchServiceError::InsufficientCredits {
                available,
                required,
            } => {
                let details = format!(
                    "Insufficient credits: available {}, required {}",
                    available, required
                );
                (StatusCode::PAYMENT_REQUIRED, details)
            }
            SearchServiceError::SearchEngine(e) => (StatusCode::INTERNAL_SERVER_ERROR, e),
            SearchServiceError::UnknownEngine(name) => (
                StatusCode::BAD_REQUEST,
                format!("unknown search engine: {name}"),
            ),
            SearchServiceError::SmartSearchFailed(detail) => (
                StatusCode::INTERNAL_SERVER_ERROR,
                format!("smart search: {detail}"),
            ),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::domain::repositories::credits_repository::CreditsRepositoryError;
    use crate::domain::repositories::task_repository::RepositoryError;

    // From<SearchServiceError> mapping tests

    #[test]
    fn test_validation_error_maps_to_bad_request() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let err = SearchServiceError::ValidationError("invalid query".to_string());
        let (status, msg) = <(StatusCode, String)>::from(err);
        assert_eq!(status, StatusCode::BAD_REQUEST);
        assert_eq!(msg, "invalid query");
    }

    #[test]
    fn test_repository_error_maps_to_internal_server_error() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let err = SearchServiceError::Repository(RepositoryError::Database(anyhow::anyhow!(
            "db connection failed"
        )));
        let (status, msg) = <(StatusCode, String)>::from(err);
        assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
        assert!(msg.contains("db connection failed"));
    }

    #[test]
    fn test_repository_not_found_maps_to_internal_server_error() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let err = SearchServiceError::Repository(RepositoryError::NotFound);
        let (status, _msg) = <(StatusCode, String)>::from(err);
        assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
    }

    #[test]
    fn test_credits_repository_error_maps_to_internal_server_error() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let err = SearchServiceError::CreditsRepository(CreditsRepositoryError::DatabaseError(
            "credits db error".to_string(),
        ));
        let (status, msg) = <(StatusCode, String)>::from(err);
        assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
        assert!(msg.contains("credits db error"));
    }

    #[test]
    fn test_credits_not_found_maps_to_internal_server_error() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let team_id = crate::domain::id::Id::generate();
        let err =
            SearchServiceError::CreditsRepository(CreditsRepositoryError::CreditsNotFound(team_id));
        let (status, _msg) = <(StatusCode, String)>::from(err);
        assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
    }

    #[test]
    fn test_insufficient_credits_maps_to_payment_required() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let err = SearchServiceError::InsufficientCredits {
            available: 5,
            required: 10,
        };
        let (status, msg) = <(StatusCode, String)>::from(err);
        assert_eq!(status, StatusCode::PAYMENT_REQUIRED);
        assert!(msg.contains("Insufficient credits"));
        assert!(msg.contains("available 5"));
        assert!(msg.contains("required 10"));
    }

    #[test]
    fn test_insufficient_credits_zero_available() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let err = SearchServiceError::InsufficientCredits {
            available: 0,
            required: 1,
        };
        let (status, msg) = <(StatusCode, String)>::from(err);
        assert_eq!(status, StatusCode::PAYMENT_REQUIRED);
        assert!(msg.contains("available 0"));
    }

    #[test]
    fn test_search_engine_error_maps_to_internal_server_error() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let err = SearchServiceError::SearchEngine("rate limited by Google".to_string());
        let (status, msg) = <(StatusCode, String)>::from(err);
        assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
        assert_eq!(msg, "rate limited by Google");
    }

    // SearchRequestDto construction tests

    #[test]
    fn test_search_request_dto_minimal() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let json = r#"{"query":"rust web scraping"}"#;
        let dto: SearchRequestDto = serde_json::from_str(json).unwrap();
        assert_eq!(dto.query, "rust web scraping");
        assert!(dto.engine.is_none());
        assert!(dto.sources.is_none());
        assert!(dto.limit.is_none());
        assert!(dto.lang.is_none());
        assert!(dto.country.is_none());
        assert!(dto.crawl_config.is_none());
        assert!(dto.crawl_results.is_none());
        assert!(dto.sync_wait_ms.is_none());
    }

    #[test]
    fn test_search_request_dto_full() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let json = r#"{
            "query": "rust async",
            "engine": "google",
            "sources": ["google", "bing"],
            "limit": 10,
            "lang": "en",
            "country": "US",
            "crawl_results": true,
            "sync_wait_ms": 5000,
            "crawl_config": {
                "max_depth": 2,
                "include_patterns": ["/blog/*"],
                "exclude_patterns": ["/admin/*"],
                "strategy": "bfs",
                "crawl_delay_ms": 1000,
                "max_concurrency": 5,
                "proxy": "http://proxy:8080",
                "headers": {"X-Custom": "value"}
            }
        }"#;
        let dto: SearchRequestDto = serde_json::from_str(json).unwrap();
        assert_eq!(dto.query, "rust async");
        assert_eq!(dto.engine.as_deref(), Some("google"));
        assert!(dto.sources.is_some());
        assert_eq!(dto.sources.as_ref().unwrap().len(), 2);
        assert_eq!(dto.limit, Some(10));
        assert_eq!(dto.lang.as_deref(), Some("en"));
        assert_eq!(dto.country.as_deref(), Some("US"));
        assert_eq!(dto.crawl_results, Some(true));
        assert_eq!(dto.sync_wait_ms, Some(5000));
        assert!(dto.crawl_config.is_some());
    }

    #[test]
    fn test_search_request_dto_deny_unknown_fields() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let json = r#"{"query":"test","unknown_field":42}"#;
        let result: Result<SearchRequestDto, _> = serde_json::from_str(json);
        assert!(result.is_err(), "unknown fields should be rejected");
    }

    #[test]
    fn test_search_request_dto_with_sources_alias() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let json = r#"{"query":"test","sources":["google","bing","baidu"]}"#;
        let dto: SearchRequestDto = serde_json::from_str(json).unwrap();
        assert_eq!(dto.sources.as_ref().unwrap().len(), 3);
    }

    #[test]
    fn test_search_request_dto_with_crawl_results_false() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let json = r#"{"query":"test","crawl_results":false}"#;
        let dto: SearchRequestDto = serde_json::from_str(json).unwrap();
        assert_eq!(dto.crawl_results, Some(false));
    }

    #[test]
    fn test_search_request_dto_with_crawl_config_minimal() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let json = r#"{"query":"test","crawl_config":{"max_depth":1}}"#;
        let dto: SearchRequestDto = serde_json::from_str(json).unwrap();
        let config = dto.crawl_config.unwrap();
        assert_eq!(config.max_depth, 1);
        assert!(config.strategy.is_none());
        assert!(config.max_concurrency.is_none());
    }

    // SearchResponseDto construction

    #[test]
    fn test_search_response_dto_construction() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let response = SearchResponseDto {
            query: "test query".to_string(),
            results: vec![],
            crawl_id: None,
            credits_used: 5,
        };
        let json = serde_json::to_string(&response).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed["query"], "test query");
        assert_eq!(parsed["results"].as_array().unwrap().len(), 0);
        assert!(parsed["crawl_id"].is_null());
        assert_eq!(parsed["credits_used"], 5);
    }

    #[test]
    fn test_search_response_dto_with_results() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let response = SearchResponseDto {
            query: "rust".to_string(),
            results: vec![
                SearchResultDto {
                    title: "Rust Programming".to_string(),
                    url: "https://rust-lang.org".to_string(),
                    description: Some("Official site".to_string()),
                    engine: Some("google".to_string()),
                    score: None,
                },
                SearchResultDto {
                    title: "Learn Rust".to_string(),
                    url: "https://doc.rust-lang.org".to_string(),
                    description: None,
                    engine: Some("bing".to_string()),
                    score: None,
                },
            ],
            crawl_id: Some(crate::domain::id::Id::generate()),
            credits_used: 1,
        };
        let json = serde_json::to_string(&response).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed["results"].as_array().unwrap().len(), 2);
        assert_eq!(parsed["results"][0]["title"], "Rust Programming");
        assert!(parsed["results"][1]["description"].is_null());
    }

    // SearchResultDto tests

    #[test]
    fn test_search_result_dto_serialization() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let result = SearchResultDto {
            title: "Test".to_string(),
            url: "https://example.com".to_string(),
            description: Some("A test result".to_string()),
            engine: Some("google".to_string()),
            score: None,
        };
        let json = serde_json::to_string(&result).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed["title"], "Test");
        assert_eq!(parsed["url"], "https://example.com");
        assert_eq!(parsed["description"], "A test result");
        assert_eq!(parsed["engine"], "google");
    }

    #[test]
    fn test_search_result_dto_clone() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let result = SearchResultDto {
            title: "Test".to_string(),
            url: "https://example.com".to_string(),
            description: None,
            engine: None,
            score: None,
        };
        let cloned = result.clone();
        assert_eq!(result.title, cloned.title);
        assert_eq!(result.url, cloned.url);
        assert_eq!(result.description, cloned.description);
        assert_eq!(result.engine, cloned.engine);
    }

    #[test]
    fn test_search_result_dto_debug() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let result = SearchResultDto {
            title: "Debug Test".to_string(),
            url: "https://debug.com".to_string(),
            description: Some("debugging".to_string()),
            engine: Some("baidu".to_string()),
            score: None,
        };
        let debug = format!("{:?}", result);
        assert!(debug.contains("SearchResultDto"));
        assert!(debug.contains("Debug Test"));
        assert!(debug.contains("https://debug.com"));
    }

    #[test]
    fn test_search_result_dto_deserialization() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let json = r#"{"title":"Test","url":"https://example.com","description":"desc","engine":"google"}"#;
        let result: SearchResultDto = serde_json::from_str(json).unwrap();
        assert_eq!(result.title, "Test");
        assert_eq!(result.url, "https://example.com");
        assert_eq!(result.description.as_deref(), Some("desc"));
        assert_eq!(result.engine.as_deref(), Some("google"));
    }

    #[test]
    fn test_search_result_dto_deserialization_without_optional_fields() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let json = r#"{"title":"Test","url":"https://example.com"}"#;
        let result: SearchResultDto = serde_json::from_str(json).unwrap();
        assert_eq!(result.title, "Test");
        assert!(result.description.is_none());
        assert!(result.engine.is_none());
    }

    // SearchQuery construction

    #[test]
    fn test_search_query_from_dto_no_crawl_config() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let dto = SearchRequestDto {
            query: "test".to_string(),
            engine: Some("google".to_string()),
            sources: Some(vec!["google".to_string()]),
            limit: Some(10),
            lang: Some("en".to_string()),
            country: Some("US".to_string()),
            crawl_config: None,
            crawl_results: Some(true),
            sync_wait_ms: Some(5000),
        };
        // Simulate the handler's conversion to SearchQuery
        let search_query = SearchQuery {
            query: dto.query,
            limit: dto.limit,
            lang: dto.lang,
            country: dto.country,
            engine: dto.engine,
            sources: dto.sources,
            crawl_results: dto.crawl_results,
            crawl_config: dto.crawl_config.map(|c| {
                crate::domain::services::search_service::SearchCrawlConfig {
                    max_depth: c.max_depth,
                    include_patterns: c.include_patterns,
                    exclude_patterns: c.exclude_patterns,
                    strategy: c.strategy.unwrap_or_else(|| "bfs".to_string()),
                    crawl_delay_ms: c.crawl_delay_ms,
                    max_concurrency: c.max_concurrency.unwrap_or(10),
                    headers: c.headers,
                    proxy: c.proxy,
                    extraction_rules: c.extraction_rules,
                    domain_blacklist: Vec::new(),
                }
            }),
        };
        assert_eq!(search_query.query, "test");
        assert!(search_query.crawl_config.is_none());
    }

    #[test]
    fn test_search_query_from_dto_with_crawl_config_defaults() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let dto = SearchRequestDto {
            query: "test".to_string(),
            engine: None,
            sources: None,
            limit: None,
            lang: None,
            country: None,
            crawl_config: Some(crate::application::dto::crawl_request::CrawlConfigDto {
                max_depth: 3,
                include_patterns: None,
                exclude_patterns: None,
                strategy: None, // Should default to "bfs"
                crawl_delay_ms: None,
                max_concurrency: None, // Should default to 10
                max_pages: None,
                proxy: None,
                headers: None,
                extraction_rules: None,
                extraction_prompt: None,
                extraction_schema: None,
            }),
            crawl_results: None,
            sync_wait_ms: None,
        };
        let search_query = SearchQuery {
            query: dto.query,
            limit: dto.limit,
            lang: dto.lang,
            country: dto.country,
            engine: dto.engine,
            sources: dto.sources,
            crawl_results: dto.crawl_results,
            crawl_config: dto.crawl_config.map(|c| {
                crate::domain::services::search_service::SearchCrawlConfig {
                    max_depth: c.max_depth,
                    include_patterns: c.include_patterns,
                    exclude_patterns: c.exclude_patterns,
                    strategy: c.strategy.unwrap_or_else(|| "bfs".to_string()),
                    crawl_delay_ms: c.crawl_delay_ms,
                    max_concurrency: c.max_concurrency.unwrap_or(10),
                    headers: c.headers,
                    proxy: c.proxy,
                    extraction_rules: c.extraction_rules,
                    domain_blacklist: Vec::new(),
                }
            }),
        };
        let config = search_query.crawl_config.unwrap();
        assert_eq!(config.max_depth, 3);
        assert_eq!(config.strategy, "bfs"); // default
        assert_eq!(config.max_concurrency, 10); // default
    }

    #[test]
    fn test_search_query_from_dto_with_crawl_config_explicit_values() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let dto = SearchRequestDto {
            query: "test".to_string(),
            engine: None,
            sources: None,
            limit: None,
            lang: None,
            country: None,
            crawl_config: Some(crate::application::dto::crawl_request::CrawlConfigDto {
                max_depth: 5,
                include_patterns: Some(vec!["/api/*".to_string()]),
                exclude_patterns: Some(vec!["/admin/*".to_string()]),
                strategy: Some("dfs".to_string()),
                crawl_delay_ms: Some(2000),
                max_concurrency: Some(20),
                max_pages: None,
                proxy: Some("http://proxy:8080".to_string()),
                headers: Some(serde_json::json!({"Accept": "text/html"})),
                extraction_rules: None,
                extraction_prompt: None,
                extraction_schema: None,
            }),
            crawl_results: None,
            sync_wait_ms: None,
        };
        let search_query = SearchQuery {
            query: dto.query,
            limit: dto.limit,
            lang: dto.lang,
            country: dto.country,
            engine: dto.engine,
            sources: dto.sources,
            crawl_results: dto.crawl_results,
            crawl_config: dto.crawl_config.map(|c| {
                crate::domain::services::search_service::SearchCrawlConfig {
                    max_depth: c.max_depth,
                    include_patterns: c.include_patterns,
                    exclude_patterns: c.exclude_patterns,
                    strategy: c.strategy.unwrap_or_else(|| "bfs".to_string()),
                    crawl_delay_ms: c.crawl_delay_ms,
                    max_concurrency: c.max_concurrency.unwrap_or(10),
                    headers: c.headers,
                    proxy: c.proxy,
                    extraction_rules: c.extraction_rules,
                    domain_blacklist: Vec::new(),
                }
            }),
        };
        let config = search_query.crawl_config.unwrap();
        assert_eq!(config.max_depth, 5);
        assert_eq!(config.strategy, "dfs"); // explicit, not default
        assert_eq!(config.max_concurrency, 20); // explicit, not default
        assert_eq!(config.crawl_delay_ms, Some(2000));
        assert!(config.include_patterns.is_some());
        assert!(config.exclude_patterns.is_some());
        assert!(config.proxy.is_some());
        assert!(config.headers.is_some());
    }

    // Additional From<SearchServiceError> tests

    #[test]
    fn test_validation_error_empty_message() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let err = SearchServiceError::ValidationError(String::new());
        let (status, msg) = <(StatusCode, String)>::from(err);
        assert_eq!(status, StatusCode::BAD_REQUEST);
        assert!(msg.is_empty());
    }

    #[test]
    fn test_insufficient_credits_large_numbers() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let err = SearchServiceError::InsufficientCredits {
            available: 999999,
            required: 1000000,
        };
        let (status, msg) = <(StatusCode, String)>::from(err);
        assert_eq!(status, StatusCode::PAYMENT_REQUIRED);
        assert!(msg.contains("999999"));
        assert!(msg.contains("1000000"));
    }

    #[test]
    fn test_insufficient_credits_negative_available() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let err = SearchServiceError::InsufficientCredits {
            available: -5,
            required: 10,
        };
        let (status, msg) = <(StatusCode, String)>::from(err);
        assert_eq!(status, StatusCode::PAYMENT_REQUIRED);
        assert!(msg.contains("-5"));
    }

    #[test]
    fn test_search_engine_error_empty_string() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let err = SearchServiceError::SearchEngine(String::new());
        let (status, msg) = <(StatusCode, String)>::from(err);
        assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
        assert!(msg.is_empty());
    }

    #[test]
    fn test_repository_error_not_found_variant() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let err = SearchServiceError::Repository(RepositoryError::NotFound);
        let (status, _msg) = <(StatusCode, String)>::from(err);
        assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
    }

    #[test]
    fn test_credits_repository_insufficient_credits_variant() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let team_id = crate::domain::id::Id::generate();
        let err =
            SearchServiceError::CreditsRepository(CreditsRepositoryError::InsufficientCredits {
                available: 0,
                required: 10,
            });
        let (status, _msg) = <(StatusCode, String)>::from(err);
        assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
        let _ = team_id; // suppress unused warning
    }

    // sync_wait_ms default logic

    #[test]
    fn test_sync_wait_ms_default_when_none() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let dto = SearchRequestDto {
            query: "test".to_string(),
            engine: None,
            sources: None,
            limit: None,
            lang: None,
            country: None,
            crawl_config: None,
            crawl_results: None,
            sync_wait_ms: None,
        };
        let sync_wait_ms = dto
            .sync_wait_ms
            .unwrap_or(crawl_task::DEFAULT_TIMEOUT_MS as u32);
        assert_eq!(sync_wait_ms, 5000);
    }

    #[test]
    fn test_sync_wait_ms_custom_when_some() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let dto = SearchRequestDto {
            query: "test".to_string(),
            engine: None,
            sources: None,
            limit: None,
            lang: None,
            country: None,
            crawl_config: None,
            crawl_results: None,
            sync_wait_ms: Some(10000),
        };
        let sync_wait_ms = dto
            .sync_wait_ms
            .unwrap_or(crawl_task::DEFAULT_TIMEOUT_MS as u32);
        assert_eq!(sync_wait_ms, 10000);
    }

    #[test]
    fn test_sync_wait_ms_zero() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let dto = SearchRequestDto {
            query: "test".to_string(),
            engine: None,
            sources: None,
            limit: None,
            lang: None,
            country: None,
            crawl_config: None,
            crawl_results: None,
            sync_wait_ms: Some(0),
        };
        let sync_wait_ms = dto
            .sync_wait_ms
            .unwrap_or(crawl_task::DEFAULT_TIMEOUT_MS as u32);
        assert_eq!(sync_wait_ms, 0);
    }

    // SearchResponseDto deserialization

    #[test]
    fn test_search_response_dto_deserialization() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let json = r#"{"query":"test","results":[],"crawl_id":null,"credits_used":0}"#.to_string();
        let dto: SearchResponseDto = serde_json::from_str(&json).unwrap();
        assert_eq!(dto.query, "test");
        assert!(dto.results.is_empty());
        assert!(dto.crawl_id.is_none());
        assert_eq!(dto.credits_used, 0);
    }

    #[test]
    fn test_search_response_dto_with_crawl_id() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let crawl_id = crate::domain::id::Id::generate();
        let json = format!(
            r#"{{"query":"test","results":[],"crawl_id":"{}","credits_used":3}}"#,
            crawl_id
        );
        let dto: SearchResponseDto = serde_json::from_str(&json).unwrap();
        assert_eq!(dto.crawl_id, Some(crawl_id));
        assert_eq!(dto.credits_used, 3);
    }

    #[test]
    fn test_search_response_dto_with_results_deserialization() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let json = r#"{
            "query": "rust",
            "results": [
                {"title":"Result 1","url":"https://1.com","description":"desc 1","engine":"google"},
                {"title":"Result 2","url":"https://2.com","description":null,"engine":"bing"}
            ],
            "crawl_id": null,
            "credits_used": 2
        }"#;
        let dto: SearchResponseDto = serde_json::from_str(json).unwrap();
        assert_eq!(dto.query, "rust");
        assert_eq!(dto.results.len(), 2);
        assert_eq!(dto.results[0].title, "Result 1");
        assert_eq!(dto.results[1].description, None);
    }

    // SearchResponseDto serialization roundtrip

    #[test]
    fn test_search_response_dto_serialization_roundtrip() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let original = SearchResponseDto {
            query: "roundtrip test".to_string(),
            results: vec![SearchResultDto {
                title: "Title".to_string(),
                url: "https://example.com".to_string(),
                description: Some("Desc".to_string()),
                engine: Some("google".to_string()),
                score: None,
            }],
            crawl_id: Some(crate::domain::id::Id::generate()),
            credits_used: 7,
        };
        let json = serde_json::to_string(&original).unwrap();
        let deserialized: SearchResponseDto = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized.query, original.query);
        assert_eq!(deserialized.results.len(), 1);
        assert_eq!(deserialized.results[0].title, "Title");
        assert_eq!(deserialized.credits_used, 7);
    }

    // SearchServiceError Display trait

    #[test]
    fn test_search_service_error_validation_display() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let err = SearchServiceError::ValidationError("bad query".to_string());
        let display = format!("{}", err);
        assert!(display.contains("bad query"));
    }

    #[test]
    fn test_search_service_error_insufficient_credits_display() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let err = SearchServiceError::InsufficientCredits {
            available: 5,
            required: 10,
        };
        let display = format!("{}", err);
        // The error message should contain information about credits
        assert!(display.contains("5") || display.contains("10") || display.contains("credit"));
    }

    #[test]
    fn test_search_service_error_search_engine_display() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let err = SearchServiceError::SearchEngine("engine timeout".to_string());
        let display = format!("{}", err);
        assert!(display.contains("engine timeout"));
    }

    // SearchRequestDto with empty query

    #[test]
    fn test_search_request_dto_empty_query() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let json = r#"{"query":""}"#;
        let dto: SearchRequestDto = serde_json::from_str(json).unwrap();
        assert_eq!(dto.query, "");
    }

    #[test]
    fn test_search_request_dto_long_query() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let long_query = "a".repeat(1000);
        let json = serde_json::json!({ "query": long_query }).to_string();
        let dto: SearchRequestDto = serde_json::from_str(&json).unwrap();
        assert_eq!(dto.query.len(), 1000);
    }

    // SearchRequestDto with special characters

    #[test]
    fn test_search_request_dto_with_unicode_query() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let json = r#"{"query":"中文搜索 日本語 한국어"}"#;
        let dto: SearchRequestDto = serde_json::from_str(json).unwrap();
        assert!(dto.query.contains("中文"));
        assert!(dto.query.contains("日本語"));
    }

    #[test]
    fn test_search_request_dto_with_special_chars_query() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let json = r#"{"query":"test \"quotes\" & <html>"}"#;
        let dto: SearchRequestDto = serde_json::from_str(json).unwrap();
        assert!(dto.query.contains("quotes"));
        assert!(dto.query.contains("<html>"));
    }

    // SearchRequestDto with limit edge cases

    #[test]
    fn test_search_request_dto_with_limit_zero() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let json = r#"{"query":"test","limit":0}"#;
        let dto: SearchRequestDto = serde_json::from_str(json).unwrap();
        assert_eq!(dto.limit, Some(0));
    }

    #[test]
    fn test_search_request_dto_with_large_limit() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let json = r#"{"query":"test","limit":4294967295}"#;
        let dto: SearchRequestDto = serde_json::from_str(json).unwrap();
        assert_eq!(dto.limit, Some(u32::MAX));
    }

    // SearchQuery with all fields None

    #[test]
    fn test_search_query_all_none() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let search_query = SearchQuery {
            query: "minimal".to_string(),
            limit: None,
            lang: None,
            country: None,
            engine: None,
            sources: None,
            crawl_results: None,
            crawl_config: None,
        };
        assert_eq!(search_query.query, "minimal");
        assert!(search_query.limit.is_none());
        assert!(search_query.crawl_config.is_none());
    }

    // crawl_config conversion with extraction_rules

    #[test]
    fn test_search_query_from_dto_with_crawl_config_extraction_rules() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let dto = SearchRequestDto {
            query: "test".to_string(),
            engine: None,
            sources: None,
            limit: None,
            lang: None,
            country: None,
            crawl_config: Some(crate::application::dto::crawl_request::CrawlConfigDto {
                max_depth: 2,
                include_patterns: None,
                exclude_patterns: None,
                strategy: None,
                crawl_delay_ms: None,
                max_concurrency: None,
                max_pages: None,
                proxy: None,
                headers: None,
                extraction_rules: Some(std::collections::HashMap::new()),
                extraction_prompt: None,
                extraction_schema: None,
            }),
            crawl_results: None,
            sync_wait_ms: None,
        };
        let search_query = SearchQuery {
            query: dto.query,
            limit: dto.limit,
            lang: dto.lang,
            country: dto.country,
            engine: dto.engine,
            sources: dto.sources,
            crawl_results: dto.crawl_results,
            crawl_config: dto.crawl_config.map(|c| {
                crate::domain::services::search_service::SearchCrawlConfig {
                    max_depth: c.max_depth,
                    include_patterns: c.include_patterns,
                    exclude_patterns: c.exclude_patterns,
                    strategy: c.strategy.unwrap_or_else(|| "bfs".to_string()),
                    crawl_delay_ms: c.crawl_delay_ms,
                    max_concurrency: c.max_concurrency.unwrap_or(10),
                    headers: c.headers,
                    proxy: c.proxy,
                    extraction_rules: c.extraction_rules,
                    domain_blacklist: Vec::new(),
                }
            }),
        };
        let config = search_query.crawl_config.unwrap();
        assert_eq!(config.max_depth, 2);
        assert_eq!(config.strategy, "bfs"); // default
        assert_eq!(config.max_concurrency, 10); // default
        assert!(config.extraction_rules.is_some());
    }

    // SearchRequestDto with multiple sources

    #[test]
    fn test_search_request_dto_with_multiple_sources() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let json = r#"{
            "query": "test",
            "sources": ["google", "bing", "baidu", "sogou"]
        }"#;
        let dto: SearchRequestDto = serde_json::from_str(json).unwrap();
        assert_eq!(dto.sources.as_ref().unwrap().len(), 4);
    }

    // SearchRequestDto with crawl_results false

    #[test]
    fn test_search_request_dto_crawl_results_false_no_crawl_config() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let json = r#"{"query":"test","crawl_results":false}"#;
        let dto: SearchRequestDto = serde_json::from_str(json).unwrap();
        assert_eq!(dto.crawl_results, Some(false));
        assert!(dto.crawl_config.is_none());
    }

    // From<SearchServiceError> with specific messages

    #[test]
    fn test_validation_error_with_special_characters() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let err = SearchServiceError::ValidationError("error with <>&\"".to_string());
        let (status, msg) = <(StatusCode, String)>::from(err);
        assert_eq!(status, StatusCode::BAD_REQUEST);
        assert!(msg.contains("<"));
        assert!(msg.contains(">"));
    }

    #[test]
    fn test_search_engine_error_with_url() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let err =
            SearchServiceError::SearchEngine("failed to fetch https://google.com".to_string());
        let (status, msg) = <(StatusCode, String)>::from(err);
        assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
        assert!(msg.contains("https://google.com"));
    }

    // SearchResponseDto with empty results

    #[test]
    fn test_search_response_dto_empty_results() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let response = SearchResponseDto {
            query: "empty".to_string(),
            results: vec![],
            crawl_id: None,
            credits_used: 0,
        };
        let json = serde_json::to_string(&response).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed["results"].as_array().unwrap().len(), 0);
    }

    // SearchRequestDto serialization

    #[test]
    fn test_search_request_dto_serialization() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let dto = SearchRequestDto {
            query: "serialize test".to_string(),
            engine: Some("google".to_string()),
            sources: Some(vec!["google".to_string()]),
            limit: Some(10),
            lang: Some("en".to_string()),
            country: Some("US".to_string()),
            crawl_config: None,
            crawl_results: Some(true),
            sync_wait_ms: Some(3000),
        };
        let json = serde_json::to_string(&dto).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed["query"], "serialize test");
        assert_eq!(parsed["engine"], "google");
        assert_eq!(parsed["limit"], 10);
        assert_eq!(parsed["crawl_results"], true);
        assert_eq!(parsed["sync_wait_ms"], 3000);
    }

    // Handler test infrastructure

    use crate::domain::auth::ApiKeyScope;
    use crate::domain::models::{CreditsTransactionType, Task, TaskStatus, TaskType};
    use crate::domain::repositories::task_repository::{TaskQueryParams, TaskRepository};
    use crate::domain::services::rate_limiting_service::{
        BacklogService, ConcurrencyConfig, ConcurrencyControlService, ConcurrencyResult,
        QuotaService, RateLimitConfig, RateLimitResult, RateLimitService, RateLimitingError,
        RateLimitingService,
    };
    use crate::domain::services::search_service::{
        SearchResponse as DomainSearchResponse, SearchResult as DomainSearchResult,
        SearchServiceTrait,
    };
    use async_trait::async_trait;
    use dbnexus::DbPool;
    use std::collections::HashSet;
    use std::sync::Mutex;

    /// Construct a lazy `DbPool` that does not connect to any database.
    fn make_test_db_pool() -> Arc<DbPool> {
        // 统一走共享 helper:每调用独立池(min=0 无预热、max=4),
        // 避免预热连接绑定到构造临时 runtime 而失效(test_helpers 说明)。
        crate::common::test_helpers::create_test_db_pool()
    }

    /// Build an `AuthState` suitable for handler unit tests.
    fn make_test_auth_state() -> AuthState {
        AuthState::new(
            make_test_db_pool(),
            crate::domain::id::Id::generate(),
            crate::domain::id::Id::generate(),
            ApiKeyScope::default(),
        )
    }

    fn test_locale() -> Locale {
        "en-US".parse().unwrap()
    }

    fn test_bundle() -> Arc<I18nBundle> {
        Arc::new(I18nBundle::load("en-US", &["en-US", "zh-CN"]).unwrap())
    }

    /// Build a sample domain SearchResponse for testing.
    fn make_search_response(crawl_id: Option<crate::domain::id::Id>) -> DomainSearchResponse {
        DomainSearchResponse {
            query: "test query".to_string(),
            results: vec![DomainSearchResult {
                title: "Test Result".to_string(),
                url: "https://example.com".to_string(),
                description: Some("Test description".to_string()),
                engine: "google".to_string(),
                score: None,
            }],
            crawl_id,
            credits_used: 1,
        }
    }

    /// Build a minimal SearchRequestDto for testing.
    fn make_search_request_dto(sync_wait_ms: Option<u32>) -> SearchRequestDto {
        SearchRequestDto {
            query: "test query".to_string(),
            engine: None,
            sources: None,
            limit: None,
            lang: None,
            country: None,
            crawl_config: None,
            crawl_results: None,
            sync_wait_ms,
        }
    }

    /// Build a Task for testing with the given team_id and status.
    fn make_test_task(team_id: crate::domain::id::Id, status: TaskStatus) -> Task {
        let now = chrono::Utc::now();
        Task {
            id: crate::domain::id::Id::generate(),
            task_type: TaskType::Scrape,
            status,
            priority: 0,
            team_id,
            api_key_id: crate::domain::id::Id::generate(),
            url: "https://example.com".to_string(),
            payload: serde_json::Value::Null,
            retry_count: 0,
            attempt_count: 0,
            max_retries: 3,
            scheduled_at: None,
            expires_at: None,
            created_at: now,
            started_at: None,
            completed_at: None,
            crawl_id: None,
            updated_at: now,
            lock_token: None,
            lock_expires_at: None,
        }
    }

    struct MockSearchService {
        search_result: Mutex<Option<Result<DomainSearchResponse, SearchServiceError>>>,
    }

    impl MockSearchService {
        fn new_success(response: DomainSearchResponse) -> Self {
            Self {
                search_result: Mutex::new(Some(Ok(response))),
            }
        }

        fn new_error(err: SearchServiceError) -> Self {
            Self {
                search_result: Mutex::new(Some(Err(err))),
            }
        }

        fn new_unused() -> Self {
            Self {
                search_result: Mutex::new(None),
            }
        }
    }

    #[async_trait]
    impl SearchServiceTrait for MockSearchService {
        async fn search(
            &self,
            _team_id: crate::domain::id::Id,
            _api_key_id: crate::domain::id::Id,
            _query: SearchQuery,
        ) -> Result<DomainSearchResponse, SearchServiceError> {
            self.search_result
                .lock()
                .unwrap()
                .take()
                .expect("MockSearchService::search called but no result configured")
        }
    }

    #[allow(clippy::type_complexity)]
    struct MockTaskRepository {
        find_by_crawl_id_result: Mutex<Option<Result<Vec<Task>, RepositoryError>>>,
        query_tasks_result: Mutex<Option<Result<(Vec<Task>, u64), RepositoryError>>>,
    }

    impl MockTaskRepository {
        fn new() -> Self {
            Self {
                find_by_crawl_id_result: Mutex::new(None),
                query_tasks_result: Mutex::new(None),
            }
        }

        fn with_find_by_crawl_id(result: Result<Vec<Task>, RepositoryError>) -> Self {
            Self {
                find_by_crawl_id_result: Mutex::new(Some(result)),
                query_tasks_result: Mutex::new(None),
            }
        }

        #[allow(dead_code)]
        fn with_query_tasks(result: Result<(Vec<Task>, u64), RepositoryError>) -> Self {
            Self {
                find_by_crawl_id_result: Mutex::new(None),
                query_tasks_result: Mutex::new(Some(result)),
            }
        }

        fn with_find_and_query(
            find_result: Result<Vec<Task>, RepositoryError>,
            query_result: Result<(Vec<Task>, u64), RepositoryError>,
        ) -> Self {
            Self {
                find_by_crawl_id_result: Mutex::new(Some(find_result)),
                query_tasks_result: Mutex::new(Some(query_result)),
            }
        }
    }

    #[async_trait]
    impl TaskRepository for MockTaskRepository {
        async fn create(&self, task: &Task) -> Result<Task, RepositoryError> {
            Ok(task.clone())
        }

        async fn find_by_id(
            &self,
            _id: crate::domain::id::Id,
        ) -> Result<Option<Task>, RepositoryError> {
            Ok(None)
        }

        async fn update(&self, task: &Task) -> Result<Task, RepositoryError> {
            Ok(task.clone())
        }

        async fn acquire_next(
            &self,
            _worker_id: crate::domain::id::Id,
        ) -> Result<Option<Task>, RepositoryError> {
            Ok(None)
        }

        async fn mark_completed(
            &self,
            _id: crate::domain::id::Id,
            _lock_token: Option<crate::domain::id::Id>,
        ) -> Result<u64, RepositoryError> {
            Ok(1)
        }

        async fn mark_failed(
            &self,
            _id: crate::domain::id::Id,
            _lock_token: Option<crate::domain::id::Id>,
        ) -> Result<u64, RepositoryError> {
            Ok(1)
        }

        async fn mark_cancelled(&self, _id: crate::domain::id::Id) -> Result<u64, RepositoryError> {
            Ok(1)
        }

        async fn exists_by_url(&self, _url: &str) -> Result<bool, RepositoryError> {
            Ok(false)
        }

        async fn find_existing_urls(
            &self,
            _urls: &[String],
        ) -> Result<HashSet<String>, RepositoryError> {
            Ok(HashSet::new())
        }

        async fn reset_stuck_tasks(
            &self,
            _timeout: chrono::Duration,
        ) -> Result<u64, RepositoryError> {
            Ok(0)
        }

        async fn cancel_tasks_by_crawl_id(
            &self,
            _crawl_id: crate::domain::id::Id,
        ) -> Result<u64, RepositoryError> {
            Ok(0)
        }

        async fn expire_tasks(&self) -> Result<u64, RepositoryError> {
            Ok(0)
        }

        async fn find_by_crawl_id(
            &self,
            _crawl_id: crate::domain::id::Id,
        ) -> Result<Vec<Task>, RepositoryError> {
            match self.find_by_crawl_id_result.lock().unwrap().take() {
                Some(result) => result,
                None => Ok(vec![]),
            }
        }

        async fn query_tasks(
            &self,
            _params: TaskQueryParams,
        ) -> Result<(Vec<Task>, u64), RepositoryError> {
            match self.query_tasks_result.lock().unwrap().take() {
                Some(result) => result,
                None => Ok((vec![], 0)),
            }
        }

        async fn batch_cancel(
            &self,
            _task_ids: Vec<crate::domain::id::Id>,
            _team_id: crate::domain::id::Id,
            _force: bool,
        ) -> Result<
            (
                Vec<crate::domain::id::Id>,
                Vec<(crate::domain::id::Id, String)>,
            ),
            RepositoryError,
        > {
            Ok((vec![], vec![]))
        }

        async fn renew_lock(
            &self,
            _task_id: crate::domain::id::Id,
            _worker_id: crate::domain::id::Id,
            _extend_seconds: i64,
        ) -> Result<bool, RepositoryError> {
            Ok(true)
        }
    }

    struct MockRateLimitingService {
        rate_limit_result: RateLimitResult,
    }

    impl MockRateLimitingService {
        fn new_allowed() -> Self {
            Self {
                rate_limit_result: RateLimitResult::Allowed,
            }
        }

        fn new_denied(reason: &str) -> Self {
            Self {
                rate_limit_result: RateLimitResult::Denied {
                    reason: reason.to_string(),
                },
            }
        }

        fn new_retry_after(seconds: u64) -> Self {
            Self {
                rate_limit_result: RateLimitResult::RetryAfter {
                    retry_after_seconds: seconds,
                },
            }
        }
    }

    #[async_trait]
    impl RateLimitService for MockRateLimitingService {
        async fn check_rate_limit(
            &self,
            _api_key: &str,
            _endpoint: &str,
        ) -> Result<RateLimitResult, RateLimitingError> {
            Ok(self.rate_limit_result.clone())
        }

        async fn get_team_rate_limit_config(
            &self,
            _team_id: crate::domain::id::Id,
        ) -> Result<RateLimitConfig, RateLimitingError> {
            Ok(RateLimitConfig::default())
        }

        async fn update_team_rate_limit_config(
            &self,
            _team_id: crate::domain::id::Id,
            _config: RateLimitConfig,
        ) -> Result<(), RateLimitingError> {
            Ok(())
        }

        async fn cleanup_expired_rate_limits(&self) -> Result<u64, RateLimitingError> {
            Ok(0)
        }
    }

    #[async_trait]
    impl ConcurrencyControlService for MockRateLimitingService {
        async fn check_team_concurrency(
            &self,
            _team_id: crate::domain::id::Id,
            _task_id: crate::domain::id::Id,
        ) -> Result<ConcurrencyResult, RateLimitingError> {
            Ok(ConcurrencyResult::Allowed)
        }

        async fn release_team_concurrency_slot(
            &self,
            _team_id: crate::domain::id::Id,
            _task_id: crate::domain::id::Id,
        ) -> Result<(), RateLimitingError> {
            Ok(())
        }

        async fn get_team_current_concurrency(
            &self,
            _team_id: crate::domain::id::Id,
        ) -> Result<u32, RateLimitingError> {
            Ok(0)
        }

        async fn get_team_concurrency_config(
            &self,
            _team_id: crate::domain::id::Id,
        ) -> Result<ConcurrencyConfig, RateLimitingError> {
            Ok(ConcurrencyConfig::default())
        }

        async fn update_team_concurrency_config(
            &self,
            _team_id: crate::domain::id::Id,
            _config: ConcurrencyConfig,
        ) -> Result<(), RateLimitingError> {
            Ok(())
        }
    }

    #[async_trait]
    impl BacklogService for MockRateLimitingService {
        async fn process_backlog_tasks(
            &self,
            _team_id: crate::domain::id::Id,
        ) -> Result<u32, RateLimitingError> {
            Ok(0)
        }
    }

    #[async_trait]
    impl QuotaService for MockRateLimitingService {
        async fn check_and_deduct_quota(
            &self,
            _team_id: crate::domain::id::Id,
            _amount: i64,
            _transaction_type: CreditsTransactionType,
            _description: String,
            _reference_id: Option<crate::domain::id::Id>,
        ) -> Result<(), RateLimitingError> {
            Ok(())
        }

        async fn get_quota_balance(
            &self,
            _team_id: crate::domain::id::Id,
        ) -> Result<i64, RateLimitingError> {
            Ok(0)
        }

        async fn refund_quota(
            &self,
            _team_id: crate::domain::id::Id,
            _amount: i64,
            _description: String,
            _reference_id: Option<crate::domain::id::Id>,
        ) -> Result<(), RateLimitingError> {
            Ok(())
        }
    }

    impl RateLimitingService for MockRateLimitingService {}

    // search handler success path tests

    #[tokio::test]
    async fn test_search_handler_success_no_crawl_id() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let search_service: Arc<dyn SearchServiceTrait> =
            Arc::new(MockSearchService::new_success(make_search_response(None)));
        let task_repo: Arc<dyn TaskRepository> = Arc::new(MockTaskRepository::new());
        let rate_limit: Arc<dyn RateLimitingService> =
            Arc::new(MockRateLimitingService::new_allowed());
        let auth = make_test_auth_state();

        let response = search(
            Extension(search_service),
            Extension(task_repo),
            Extension(rate_limit),
            Extension(None::<
                Arc<dyn crate::domain::repositories::geo_restriction_repository::GeoRestrictionRepository>,
            >),
            Extension(auth),
            Extension(test_locale()),
            Extension(test_bundle()),
            Ok(Json(make_search_request_dto(Some(5000)))),
        )
        .await
        .into_response();

        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn test_search_handler_success_sync_wait_zero() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let search_service: Arc<dyn SearchServiceTrait> = Arc::new(MockSearchService::new_success(
            make_search_response(Some(crate::domain::id::Id::generate())),
        ));
        let task_repo: Arc<dyn TaskRepository> = Arc::new(MockTaskRepository::new());
        let rate_limit: Arc<dyn RateLimitingService> =
            Arc::new(MockRateLimitingService::new_allowed());
        let auth = make_test_auth_state();

        // sync_wait_ms = 0 → should skip wait_for_tasks_completion entirely
        let response = search(
            Extension(search_service),
            Extension(task_repo),
            Extension(rate_limit),
            Extension(None::<
                Arc<dyn crate::domain::repositories::geo_restriction_repository::GeoRestrictionRepository>,
            >),
            Extension(auth),
            Extension(test_locale()),
            Extension(test_bundle()),
            Ok(Json(make_search_request_dto(Some(0)))),
        )
        .await
        .into_response();

        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn test_search_handler_success_crawl_id_empty_tasks() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let crawl_id = crate::domain::id::Id::generate();
        let search_service: Arc<dyn SearchServiceTrait> = Arc::new(MockSearchService::new_success(
            make_search_response(Some(crawl_id)),
        ));
        // find_by_crawl_id returns empty vec → no wait_for_tasks_completion call
        let task_repo: Arc<dyn TaskRepository> = Arc::new(MockTaskRepository::new());
        let rate_limit: Arc<dyn RateLimitingService> =
            Arc::new(MockRateLimitingService::new_allowed());
        let auth = make_test_auth_state();

        let response = search(
            Extension(search_service),
            Extension(task_repo),
            Extension(rate_limit),
            Extension(None::<
                Arc<dyn crate::domain::repositories::geo_restriction_repository::GeoRestrictionRepository>,
            >),
            Extension(auth),
            Extension(test_locale()),
            Extension(test_bundle()),
            Ok(Json(make_search_request_dto(Some(5000)))),
        )
        .await
        .into_response();

        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn test_search_handler_success_crawl_id_with_completed_tasks() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let team_id = crate::domain::id::Id::generate();
        let crawl_id = crate::domain::id::Id::generate();
        let task = make_test_task(team_id, TaskStatus::Completed);

        let search_service: Arc<dyn SearchServiceTrait> = Arc::new(MockSearchService::new_success(
            make_search_response(Some(crawl_id)),
        ));
        // find_by_crawl_id returns non-empty vec, query_tasks returns completed tasks
        // → completion_rate >= 1.0 → wait_for_tasks_completion returns immediately
        let task_repo: Arc<dyn TaskRepository> = Arc::new(MockTaskRepository::with_find_and_query(
            Ok(vec![task.clone()]),
            Ok((vec![task], 1)),
        ));
        let rate_limit: Arc<dyn RateLimitingService> =
            Arc::new(MockRateLimitingService::new_allowed());
        let auth = make_test_auth_state();

        let response = search(
            Extension(search_service),
            Extension(task_repo),
            Extension(rate_limit),
            Extension(None::<
                Arc<dyn crate::domain::repositories::geo_restriction_repository::GeoRestrictionRepository>,
            >),
            Extension(auth),
            Extension(test_locale()),
            Extension(test_bundle()),
            Ok(Json(make_search_request_dto(Some(5000)))),
        )
        .await
        .into_response();

        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn test_search_handler_success_find_by_crawl_id_error() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let crawl_id = crate::domain::id::Id::generate();
        let search_service: Arc<dyn SearchServiceTrait> = Arc::new(MockSearchService::new_success(
            make_search_response(Some(crawl_id)),
        ));
        // find_by_crawl_id returns error → logged, response still OK
        let task_repo: Arc<dyn TaskRepository> =
            Arc::new(MockTaskRepository::with_find_by_crawl_id(Err(
                RepositoryError::Database(anyhow::anyhow!("find_by_crawl_id failed")),
            )));
        let rate_limit: Arc<dyn RateLimitingService> =
            Arc::new(MockRateLimitingService::new_allowed());
        let auth = make_test_auth_state();

        let response = search(
            Extension(search_service),
            Extension(task_repo),
            Extension(rate_limit),
            Extension(None::<
                Arc<dyn crate::domain::repositories::geo_restriction_repository::GeoRestrictionRepository>,
            >),
            Extension(auth),
            Extension(test_locale()),
            Extension(test_bundle()),
            Ok(Json(make_search_request_dto(Some(5000)))),
        )
        .await
        .into_response();

        assert_eq!(
            response.status(),
            StatusCode::OK,
            "find_by_crawl_id error should be logged but not fail the request"
        );
    }

    #[tokio::test]
    async fn test_search_handler_success_wait_for_tasks_completion_error() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let team_id = crate::domain::id::Id::generate();
        let crawl_id = crate::domain::id::Id::generate();
        let task = make_test_task(team_id, TaskStatus::Queued);

        let search_service: Arc<dyn SearchServiceTrait> = Arc::new(MockSearchService::new_success(
            make_search_response(Some(crawl_id)),
        ));
        // find_by_crawl_id returns non-empty vec, query_tasks returns error
        // → wait_for_tasks_completion returns Err → logged, response still OK
        let task_repo: Arc<dyn TaskRepository> = Arc::new(MockTaskRepository::with_find_and_query(
            Ok(vec![task]),
            Err(RepositoryError::Database(anyhow::anyhow!(
                "query_tasks failed"
            ))),
        ));
        let rate_limit: Arc<dyn RateLimitingService> =
            Arc::new(MockRateLimitingService::new_allowed());
        let auth = make_test_auth_state();

        let response = search(
            Extension(search_service),
            Extension(task_repo),
            Extension(rate_limit),
            Extension(None::<
                Arc<dyn crate::domain::repositories::geo_restriction_repository::GeoRestrictionRepository>,
            >),
            Extension(auth),
            Extension(test_locale()),
            Extension(test_bundle()),
            Ok(Json(make_search_request_dto(Some(5000)))),
        )
        .await
        .into_response();

        assert_eq!(
            response.status(),
            StatusCode::OK,
            "wait_for_tasks_completion error should be logged but not fail the request"
        );
    }

    #[tokio::test]
    async fn test_search_handler_success_default_sync_wait_ms() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let search_service: Arc<dyn SearchServiceTrait> =
            Arc::new(MockSearchService::new_success(make_search_response(None)));
        let task_repo: Arc<dyn TaskRepository> = Arc::new(MockTaskRepository::new());
        let rate_limit: Arc<dyn RateLimitingService> =
            Arc::new(MockRateLimitingService::new_allowed());
        let auth = make_test_auth_state();

        // sync_wait_ms = None → uses DEFAULT_TIMEOUT_MS (5000)
        let response = search(
            Extension(search_service),
            Extension(task_repo),
            Extension(rate_limit),
            Extension(None::<
                Arc<dyn crate::domain::repositories::geo_restriction_repository::GeoRestrictionRepository>,
            >),
            Extension(auth),
            Extension(test_locale()),
            Extension(test_bundle()),
            Ok(Json(make_search_request_dto(None))),
        )
        .await
        .into_response();

        assert_eq!(response.status(), StatusCode::OK);
    }

    // search handler rate limiting tests

    #[tokio::test]
    async fn test_search_handler_rate_limited_denied() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let search_service: Arc<dyn SearchServiceTrait> = Arc::new(MockSearchService::new_unused());
        let task_repo: Arc<dyn TaskRepository> = Arc::new(MockTaskRepository::new());
        let rate_limit: Arc<dyn RateLimitingService> =
            Arc::new(MockRateLimitingService::new_denied("too many requests"));
        let auth = make_test_auth_state();

        let response = search(
            Extension(search_service),
            Extension(task_repo),
            Extension(rate_limit),
            Extension(None::<
                Arc<dyn crate::domain::repositories::geo_restriction_repository::GeoRestrictionRepository>,
            >),
            Extension(auth),
            Extension(test_locale()),
            Extension(test_bundle()),
            Ok(Json(make_search_request_dto(Some(5000)))),
        )
        .await
        .into_response();

        assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
    }

    #[tokio::test]
    async fn test_search_handler_rate_limited_retry_after() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let search_service: Arc<dyn SearchServiceTrait> = Arc::new(MockSearchService::new_unused());
        let task_repo: Arc<dyn TaskRepository> = Arc::new(MockTaskRepository::new());
        let rate_limit: Arc<dyn RateLimitingService> =
            Arc::new(MockRateLimitingService::new_retry_after(30));
        let auth = make_test_auth_state();

        let response = search(
            Extension(search_service),
            Extension(task_repo),
            Extension(rate_limit),
            Extension(None::<
                Arc<dyn crate::domain::repositories::geo_restriction_repository::GeoRestrictionRepository>,
            >),
            Extension(auth),
            Extension(test_locale()),
            Extension(test_bundle()),
            Ok(Json(make_search_request_dto(Some(5000)))),
        )
        .await
        .into_response();

        assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
    }

    // search handler service error tests

    #[tokio::test]
    async fn test_search_handler_validation_error() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let search_service: Arc<dyn SearchServiceTrait> = Arc::new(MockSearchService::new_error(
            SearchServiceError::ValidationError("invalid query".to_string()),
        ));
        let task_repo: Arc<dyn TaskRepository> = Arc::new(MockTaskRepository::new());
        let rate_limit: Arc<dyn RateLimitingService> =
            Arc::new(MockRateLimitingService::new_allowed());
        let auth = make_test_auth_state();

        let response = search(
            Extension(search_service),
            Extension(task_repo),
            Extension(rate_limit),
            Extension(None::<
                Arc<dyn crate::domain::repositories::geo_restriction_repository::GeoRestrictionRepository>,
            >),
            Extension(auth),
            Extension(test_locale()),
            Extension(test_bundle()),
            Ok(Json(make_search_request_dto(Some(5000)))),
        )
        .await
        .into_response();

        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn test_search_handler_insufficient_credits() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let search_service: Arc<dyn SearchServiceTrait> = Arc::new(MockSearchService::new_error(
            SearchServiceError::InsufficientCredits {
                available: 0,
                required: 1,
            },
        ));
        let task_repo: Arc<dyn TaskRepository> = Arc::new(MockTaskRepository::new());
        let rate_limit: Arc<dyn RateLimitingService> =
            Arc::new(MockRateLimitingService::new_allowed());
        let auth = make_test_auth_state();

        let response = search(
            Extension(search_service),
            Extension(task_repo),
            Extension(rate_limit),
            Extension(None::<
                Arc<dyn crate::domain::repositories::geo_restriction_repository::GeoRestrictionRepository>,
            >),
            Extension(auth),
            Extension(test_locale()),
            Extension(test_bundle()),
            Ok(Json(make_search_request_dto(Some(5000)))),
        )
        .await
        .into_response();

        assert_eq!(response.status(), StatusCode::PAYMENT_REQUIRED);
    }

    #[tokio::test]
    async fn test_search_handler_search_engine_error() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let search_service: Arc<dyn SearchServiceTrait> = Arc::new(MockSearchService::new_error(
            SearchServiceError::SearchEngine("engine timeout".to_string()),
        ));
        let task_repo: Arc<dyn TaskRepository> = Arc::new(MockTaskRepository::new());
        let rate_limit: Arc<dyn RateLimitingService> =
            Arc::new(MockRateLimitingService::new_allowed());
        let auth = make_test_auth_state();

        let response = search(
            Extension(search_service),
            Extension(task_repo),
            Extension(rate_limit),
            Extension(None::<
                Arc<dyn crate::domain::repositories::geo_restriction_repository::GeoRestrictionRepository>,
            >),
            Extension(auth),
            Extension(test_locale()),
            Extension(test_bundle()),
            Ok(Json(make_search_request_dto(Some(5000)))),
        )
        .await
        .into_response();

        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
    }

    #[tokio::test]
    async fn test_search_handler_repository_error() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let search_service: Arc<dyn SearchServiceTrait> = Arc::new(MockSearchService::new_error(
            SearchServiceError::Repository(RepositoryError::Database(anyhow::anyhow!(
                "db connection failed"
            ))),
        ));
        let task_repo: Arc<dyn TaskRepository> = Arc::new(MockTaskRepository::new());
        let rate_limit: Arc<dyn RateLimitingService> =
            Arc::new(MockRateLimitingService::new_allowed());
        let auth = make_test_auth_state();

        let response = search(
            Extension(search_service),
            Extension(task_repo),
            Extension(rate_limit),
            Extension(None::<
                Arc<dyn crate::domain::repositories::geo_restriction_repository::GeoRestrictionRepository>,
            >),
            Extension(auth),
            Extension(test_locale()),
            Extension(test_bundle()),
            Ok(Json(make_search_request_dto(Some(5000)))),
        )
        .await
        .into_response();

        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
    }

    #[tokio::test]
    async fn test_search_handler_credits_repository_error() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let search_service: Arc<dyn SearchServiceTrait> = Arc::new(MockSearchService::new_error(
            SearchServiceError::CreditsRepository(CreditsRepositoryError::DatabaseError(
                "credits db error".to_string(),
            )),
        ));
        let task_repo: Arc<dyn TaskRepository> = Arc::new(MockTaskRepository::new());
        let rate_limit: Arc<dyn RateLimitingService> =
            Arc::new(MockRateLimitingService::new_allowed());
        let auth = make_test_auth_state();

        let response = search(
            Extension(search_service),
            Extension(task_repo),
            Extension(rate_limit),
            Extension(None::<
                Arc<dyn crate::domain::repositories::geo_restriction_repository::GeoRestrictionRepository>,
            >),
            Extension(auth),
            Extension(test_locale()),
            Extension(test_bundle()),
            Ok(Json(make_search_request_dto(Some(5000)))),
        )
        .await
        .into_response();

        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
    }

    #[tokio::test]
    async fn test_search_handler_repository_not_found_error() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let search_service: Arc<dyn SearchServiceTrait> = Arc::new(MockSearchService::new_error(
            SearchServiceError::Repository(RepositoryError::NotFound),
        ));
        let task_repo: Arc<dyn TaskRepository> = Arc::new(MockTaskRepository::new());
        let rate_limit: Arc<dyn RateLimitingService> =
            Arc::new(MockRateLimitingService::new_allowed());
        let auth = make_test_auth_state();

        let response = search(
            Extension(search_service),
            Extension(task_repo),
            Extension(rate_limit),
            Extension(None::<
                Arc<dyn crate::domain::repositories::geo_restriction_repository::GeoRestrictionRepository>,
            >),
            Extension(auth),
            Extension(test_locale()),
            Extension(test_bundle()),
            Ok(Json(make_search_request_dto(Some(5000)))),
        )
        .await
        .into_response();

        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
    }

    #[tokio::test]
    async fn test_search_handler_credits_not_found_error() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let team_id = crate::domain::id::Id::generate();
        let search_service: Arc<dyn SearchServiceTrait> = Arc::new(MockSearchService::new_error(
            SearchServiceError::CreditsRepository(CreditsRepositoryError::CreditsNotFound(team_id)),
        ));
        let task_repo: Arc<dyn TaskRepository> = Arc::new(MockTaskRepository::new());
        let rate_limit: Arc<dyn RateLimitingService> =
            Arc::new(MockRateLimitingService::new_allowed());
        let auth = make_test_auth_state();

        let response = search(
            Extension(search_service),
            Extension(task_repo),
            Extension(rate_limit),
            Extension(None::<
                Arc<dyn crate::domain::repositories::geo_restriction_repository::GeoRestrictionRepository>,
            >),
            Extension(auth),
            Extension(test_locale()),
            Extension(test_bundle()),
            Ok(Json(make_search_request_dto(Some(5000)))),
        )
        .await
        .into_response();

        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
    }
}