domain-status 0.2.1

Concurrent URL status checker that captures comprehensive metadata in SQLite.
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
//! JSONL export functionality.
//!
//! Exports `domain_status` data to JSONL (JSON Lines) format.
//! Each line is a complete JSON object representing one URL scan result.
//! This format is ideal for programmatic processing, piping to jq, or loading into databases.

use anyhow::Result;
use serde_json::{json, Value};
use std::io::{self, Write};

use crate::utils::IoErrorContext;

use super::bootstrap::for_each_export_row;
use super::fields;
use super::queries::IgnoreBrokenPipe;
use super::row::{build_url, parse_string_list};

/// Exports data to JSONL format (JSON Lines).
///
/// Each line is a complete JSON object with all fields for one URL scan result.
/// This format preserves nested structures better than CSV and is ideal for:
/// - Piping to `jq` for filtering/transformation
/// - Loading into databases (`MongoDB`, Elasticsearch, etc.)
/// - Programmatic processing in scripts
///
/// # Arguments
///
/// * `opts` - Export options including database path, output, and filters
///
/// # Returns
///
/// Returns the number of records exported, or an error if export fails.
///
/// # Examples
///
/// ```no_run
/// use domain_status::export::{export_jsonl, ExportFormat, ExportOptions};
/// use std::path::PathBuf;
///
/// # #[tokio::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let count = export_jsonl(&ExportOptions {
///     db_path: PathBuf::from("./domain_status.db"),
///     output: None,
///     format: ExportFormat::Jsonl,
///     run_id: Some("run_1700000000000".to_string()),
///     domain: None,
///     status: None,
///     since: None,
///     include_implied_tech: false,
/// })
/// .await?;
///
/// eprintln!("streamed {count} JSONL records");
/// # Ok(())
/// # }
/// ```
///
/// # Errors
/// Returns `Err` when the database pool cannot be created, the query fails, or writing the output fails.
#[allow(clippy::too_many_lines)] // Sequential export pipeline: DB setup, query, row serialization, output
pub async fn export_jsonl(opts: &super::ExportOptions) -> Result<usize> {
    let mut writer: Box<dyn Write> = if let Some(output_path) = opts.output.as_ref() {
        let file = tokio::fs::File::create(output_path)
            .await
            .with_path(output_path)?
            .into_std()
            .await;
        Box::new(file)
    } else {
        Box::new(IgnoreBrokenPipe::new(io::stdout()))
    };

    let record_count = for_each_export_row(opts, |export_row| {

        // Build URL
        let url = build_url(&export_row.main.final_domain);

        // Convert redirects to JSON array
        let redirect_chain: Vec<Value> = export_row
            .redirects
            .iter()
            .map(|r| {
                json!({
                    "redirect_url": r.redirect_url,
                    "sequence_order": r.sequence_order,
                    "http_status": r.http_status,
                })
            })
            .collect();

        // Build technologies from structured data (avoids comma/colon delimiter corruption)
        let technologies: Vec<Value> = export_row
            .technologies
            .iter()
            .map(|t| {
                json!({
                    "name": t.name,
                    "version": t.version.clone().map_or(Value::Null, Value::String),
                    "category": t.category.clone().map_or(Value::Null, Value::String),
                    "is_implied": t.is_implied,
                    "detection_source": t.detection_source.clone().map_or(Value::Null, Value::String),
                })
            })
            .collect();

        // Parse certificate SANs
        let certificate_sans = parse_string_list(&export_row.certificate_sans_str);

        // Parse OIDs
        let oids = parse_string_list(&export_row.oids_str);

        // Build analytics IDs from structured data (avoids comma/colon delimiter corruption)
        let analytics_ids: Vec<Value> = export_row
            .analytics_ids
            .iter()
            .map(|a| {
                json!({
                    "provider": a.provider,
                    "tracking_id": a.tracking_id
                })
            })
            .collect();

        // Build social media links with identifiers
        let social_media_links: Vec<Value> = export_row
            .social_media_links
            .iter()
            .map(|link| {
                json!({
                    "platform": link.platform,
                    "url": link.profile_url,
                    "identifier": link.identifier,
                })
            })
            .collect();

        // Parse structured data types
        let structured_data_types = parse_string_list(&export_row.structured_data_types_str);

        // Build GeoIP JSON (or null if no data)
        let geoip = if export_row.geoip.country_code.is_some()
            || export_row.geoip.asn.is_some()
            || export_row.geoip.latitude.is_some()
        {
            Some(json!({
                "country_code": export_row.geoip.country_code,
                "country_name": export_row.geoip.country_name,
                "region": export_row.geoip.region,
                "city": export_row.geoip.city,
                "latitude": export_row.geoip.latitude,
                "longitude": export_row.geoip.longitude,
                "asn": export_row.geoip.asn,
                "asn_org": export_row.geoip.asn_org,
            }))
        } else {
            None
        };

        // Build WHOIS JSON (or null if no data)
        let whois = if export_row.whois.registrar.is_some()
            || export_row.whois.creation_date_ms.is_some()
        {
            Some(json!({
                "registrar": export_row.whois.registrar,
                "creation_date_ms": export_row.whois.creation_date_ms,
                "expiration_date_ms": export_row.whois.expiration_date_ms,
                "registrant_country": export_row.whois.registrant_country,
            }))
        } else {
            None
        };

        // Build the complete JSON object
        let mut json_obj = json!({
            "url": url,
            "initial_domain": export_row.main.initial_domain,
            "final_domain": export_row.main.final_domain,
            "initial_url": export_row.main.initial_url,
            "final_url": export_row.main.final_url,
            "ip_address": export_row.main.ip_address,
            "reverse_dns": export_row.main.reverse_dns,
            "status": export_row.main.status,
            "status_description": export_row.main.status_desc,
            "response_time_ms": export_row.main.response_time,
            "title": export_row.main.title,
            "description": export_row.main.description,
            "meta_robots": export_row.main.meta_robots,
            "body_sha256": export_row.main.body_sha256,
            "content_length": export_row.main.content_length,
            "http_version": export_row.main.http_version,
            "content_type": export_row.main.content_type,
            "canonical_url": export_row.main.canonical_url,
            "body_truncated": export_row.main.body_truncated,
            "redirect_chain": redirect_chain,
            "redirect_count": export_row.redirect_count,
            "final_redirect_url": export_row.final_redirect_url,
            "technologies": technologies,
            "technology_count": export_row.technology_count,
            "tls": {
                "version": export_row.main.tls_version,
                "certificate": {
                    "subject": export_row.main.ssl_cert_subject,
                    "issuer": export_row.main.ssl_cert_issuer,
                    "valid_to": export_row.main.ssl_cert_valid_to_ms,
                    "sans": certificate_sans,
                    "san_count": export_row.certificate_san_count,
                    "oids": oids,
                },
                "cipher_suite": export_row.main.cipher_suite,
                "key_algorithm": export_row.main.key_algorithm,
                "cert_fingerprint_sha256": export_row.main.cert_fingerprint_sha256,
            },
            "dns": {
                "nameserver_count": export_row.nameserver_count,
                "nameservers": export_row.nameservers.iter().map(|ns| &ns.nameserver).collect::<Vec<_>>(),
                "txt_record_count": export_row.txt_count,
                "txt_records": export_row.txt_records.iter().map(|r| json!({"record_type": r.record_type, "content": r.record_value})).collect::<Vec<_>>(),
                "mx_record_count": export_row.mx_count,
                "mx_records": export_row.mx_records.iter().map(|r| json!({"priority": r.priority, "mail_exchange": r.mail_exchange})).collect::<Vec<_>>(),
                "cname_records": export_row.cname_records,
                "cname_count": export_row.cname_count,
                "ipv6_addresses": export_row.ipv6_addresses,
                "ipv6_count": export_row.ipv6_count,
                "caa_records": export_row.caa_records.iter().map(|r| json!({"flag": r.flag, "tag": r.tag, "value": r.value})).collect::<Vec<_>>(),
                "caa_count": export_row.caa_count,
            },
            "spf_record": export_row.main.spf_record,
            "dmarc_record": export_row.main.dmarc_record,
            "mta_sts_record": export_row.main.mta_sts_record,
            "tls_rpt_record": export_row.main.tls_rpt_record,
            "bimi_record": export_row.main.bimi_record,
            "hsts_max_age": export_row.main.hsts_max_age,
            "hsts_include_subdomains": export_row.main.hsts_include_subdomains,
            "hsts_preload": export_row.main.hsts_preload,
            "cdn_provider": export_row.main.cdn_provider,
            "script_hosts": export_row.script_hosts.iter().map(|h| json!({
                "host": h.host,
                "registrable_domain": h.registrable_domain,
                "is_first_party": h.is_first_party
            })).collect::<Vec<_>>(),
            "analytics_ids": analytics_ids,
            "analytics_count": export_row.analytics_count,
            "social_media_links": social_media_links,
            "social_media_count": export_row.social_media_count,
            "structured_data": {
                "types": structured_data_types,
                "count": export_row.structured_data_count,
                "entries": export_row.structured_data_entries.iter().map(|e| json!({"data_type": e.data_type, "property_name": e.property_name, "property_value": e.property_value})).collect::<Vec<_>>(),
            },
            "http_headers": export_row.all_http_headers.iter().map(|h| json!({"name": h.name, "value": h.value})).collect::<Vec<_>>(),
            "http_header_count": export_row.http_header_count,
            "security_headers": export_row.all_security_headers.iter().map(|h| json!({"name": h.name, "value": h.value})).collect::<Vec<_>>(),
            "security_header_count": export_row.security_header_count,
            "partial_failures": export_row.partial_failures.iter().map(|f| json!({"error_type": f.error_type, "error_message": f.error_message})).collect::<Vec<_>>(),
            "geoip": geoip,
            "whois": whois,
            "favicon": {
                "hash": export_row.favicon_hash,
                "url": export_row.favicon_url,
            },
            "timestamp": export_row.main.timestamp,
            "run_id": export_row.main.run_id,
        });

        // Add contact links and exposed secrets (built outside json! macro to avoid recursion limit)
        if let Value::Object(ref mut map) = json_obj {
            map.insert(
                "contact_links".to_string(),
                json!(export_row.contact_links.iter().map(|c| json!({"contact_type": c.contact_type, "contact_value": c.contact_value})).collect::<Vec<_>>()),
            );
            map.insert(
                "contact_link_count".to_string(),
                json!(export_row.contact_link_count),
            );
            map.insert(
                "exposed_secrets".to_string(),
                json!(export_row
                    .exposed_secrets
                    .iter()
                    .map(|s| {
                        let mut obj = json!({
                            "secret_type": s.secret_type,
                            "matched_value": s.matched_value,
                            "severity": s.severity,
                            "location": s.location,
                            "context": s.context,
                        });
                        if s.jwt_algorithm.is_some() || s.jwt_issuer.is_some() {
                            obj["jwt_claims"] = json!({
                                "algorithm": s.jwt_algorithm,
                                "issuer": s.jwt_issuer,
                                "subject": s.jwt_subject,
                                "audience": s.jwt_audience,
                                "expiration_ms": s.jwt_expiration_ms,
                                "issued_at_ms": s.jwt_issued_at_ms,
                                "header_json": s.jwt_header_json,
                                "payload_json": s.jwt_payload_json,
                            });
                        }
                        obj
                    })
                    .collect::<Vec<_>>()),
            );
            map.insert(
                "exposed_secret_count".to_string(),
                json!(export_row.exposed_secret_count),
            );
        }

        if let Value::Object(ref mut map) = json_obj {
            fields::insert_jsonl_flat_fields(map, &export_row);
        }
        serde_json::to_writer(&mut writer, &json_obj)?;
        writeln!(writer)?;

        Ok(())
    })
    .await?;

    Ok(record_count)
}

#[cfg(test)]
mod tests {
    use super::super::types::{ExportFormat, ExportOptions};
    use super::export_jsonl;
    use crate::storage::migrations::run_migrations;
    use sqlx::{Row, SqlitePool};
    use std::io::Read;
    use tempfile::NamedTempFile;

    async fn create_test_run(pool: &SqlitePool, run_id: &str) {
        sqlx::query(
            "INSERT INTO runs (run_id, start_time_ms) VALUES (?, ?)
             ON CONFLICT(run_id) DO NOTHING",
        )
        .bind(run_id)
        .bind(1704067200000i64)
        .execute(pool)
        .await
        .expect("Failed to insert test run");
    }

    async fn create_test_url_status(pool: &SqlitePool, domain: &str, status: u16) -> i64 {
        // Ensure the run exists first (FK constraint)
        create_test_run(pool, "test-run-1").await;

        sqlx::query(
            "INSERT INTO url_status (
                initial_domain, final_domain, ip_address, http_status, http_status_text,
                response_time_seconds, title, observed_at_ms, run_id
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
            RETURNING id",
        )
        .bind(domain)
        .bind(domain)
        .bind("192.0.2.1")
        .bind(status)
        .bind("OK")
        .bind(1.5f64)
        .bind("Test Page")
        .bind(1704067200000i64)
        .bind("test-run-1")
        .fetch_one(pool)
        .await
        .expect("Failed to insert test URL status")
        .get::<i64, _>(0)
    }

    #[tokio::test]
    async fn test_export_jsonl_with_real_database() {
        let temp_db = NamedTempFile::new().expect("Failed to create temp DB");
        let db_path = temp_db.path();

        // Create a real database file
        let pool = SqlitePool::connect(&format!("sqlite:{}", db_path.display()))
            .await
            .expect("Failed to create database pool");
        run_migrations(&pool)
            .await
            .expect("Failed to run migrations");

        let _url_id = create_test_url_status(&pool, "example.com", 200).await;
        drop(pool); // Close connection so export can open it

        let temp_file = NamedTempFile::new().expect("Failed to create temp file");
        let output_path = temp_file.path().to_path_buf();

        let count = export_jsonl(&ExportOptions {
            db_path: db_path.to_path_buf(),
            output: Some(output_path.clone()),
            format: ExportFormat::Jsonl,
            run_id: None,
            domain: None,
            status: None,
            since: None,
            include_implied_tech: false,
        })
        .await
        .expect("Should export successfully");

        assert_eq!(count, 1, "Should export 1 record");

        // Verify output file contains valid JSON
        let mut file = std::fs::File::open(&output_path).expect("Failed to open output file");
        let mut contents = String::new();
        file.read_to_string(&mut contents)
            .expect("Failed to read output file");

        let lines: Vec<&str> = contents.trim().split('\n').collect();
        assert_eq!(lines.len(), 1, "Should have 1 line");

        let json_obj: serde_json::Value =
            serde_json::from_str(lines[0]).expect("Should be valid JSON");
        assert_eq!(json_obj["initial_domain"], "example.com");
        assert_eq!(json_obj["final_domain"], "example.com");
        assert_eq!(json_obj["status"], 200);
    }

    #[tokio::test]
    async fn test_jsonl_includes_required_flat_export_keys() {
        use crate::export::field_inventory::URL_STATUS_REQUIRED_IN_FLAT_EXPORT;

        let temp_db = NamedTempFile::new().expect("Failed to create temp DB");
        let db_path = temp_db.path();

        let pool = SqlitePool::connect(&format!("sqlite:{}", db_path.display()))
            .await
            .expect("Failed to create database pool");
        run_migrations(&pool)
            .await
            .expect("Failed to run migrations");
        create_test_url_status(&pool, "example.com", 200).await;
        drop(pool);

        let temp_file = NamedTempFile::new().expect("Failed to create temp file");
        let output_path = temp_file.path().to_path_buf();

        export_jsonl(&ExportOptions {
            db_path: db_path.to_path_buf(),
            output: Some(output_path.clone()),
            format: ExportFormat::Jsonl,
            run_id: None,
            domain: None,
            status: None,
            since: None,
            include_implied_tech: false,
        })
        .await
        .expect("Should export successfully");

        let mut contents = String::new();
        std::fs::File::open(&output_path)
            .expect("open")
            .read_to_string(&mut contents)
            .expect("read");
        let json_obj: serde_json::Value =
            serde_json::from_str(contents.trim()).expect("valid JSON");

        // JSONL nests some TLS fields under `tls` (unlike flat CSV/Parquet).
        fn jsonl_has_required_field(obj: &serde_json::Value, name: &str) -> bool {
            if obj.get(name).is_some() {
                return true;
            }
            if name == "cert_fingerprint_sha256" {
                return obj.pointer("/tls/cert_fingerprint_sha256").is_some();
            }
            false
        }

        let mut missing = Vec::new();
        for key in URL_STATUS_REQUIRED_IN_FLAT_EXPORT {
            if !jsonl_has_required_field(&json_obj, key) {
                missing.push(*key);
            }
        }
        assert!(
            missing.is_empty(),
            "JSONL missing required fields: {missing:?}"
        );
    }

    #[tokio::test]
    async fn test_export_jsonl_filter_by_run_id() {
        let temp_db = NamedTempFile::new().expect("Failed to create temp DB");
        let db_path = temp_db.path();

        let pool = SqlitePool::connect(&format!("sqlite:{}", db_path.display()))
            .await
            .expect("Failed to create database pool");
        run_migrations(&pool)
            .await
            .expect("Failed to run migrations");

        // Create records with different run_ids
        create_test_url_status(&pool, "example.com", 200).await;

        // Create second run first (FK constraint)
        create_test_run(&pool, "test-run-2").await;

        sqlx::query(
            "INSERT INTO url_status (
                initial_domain, final_domain, ip_address, http_status, http_status_text,
                response_time_seconds, title, observed_at_ms, run_id
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
            RETURNING id",
        )
        .bind("other.com")
        .bind("other.com")
        .bind("192.0.2.2")
        .bind(200)
        .bind("OK")
        .bind(1.5f64)
        .bind("Other Page")
        .bind(1704067200000i64)
        .bind("test-run-2")
        .fetch_one(&pool)
        .await
        .expect("Failed to insert");

        drop(pool);

        let temp_file = NamedTempFile::new().expect("Failed to create temp file");
        let output_path = temp_file.path().to_path_buf();

        let count = export_jsonl(&ExportOptions {
            db_path: db_path.to_path_buf(),
            output: Some(output_path.clone()),
            format: ExportFormat::Jsonl,
            run_id: Some("test-run-1".to_string()),
            domain: None,
            status: None,
            since: None,
            include_implied_tech: false,
        })
        .await
        .expect("Should export successfully");

        assert_eq!(count, 1, "Should export only 1 record matching run_id");

        let mut file = std::fs::File::open(&output_path).expect("Failed to open output file");
        let mut contents = String::new();
        file.read_to_string(&mut contents)
            .expect("Failed to read output file");

        let lines: Vec<&str> = contents.trim().split('\n').collect();
        assert_eq!(lines.len(), 1);
        let json_obj: serde_json::Value =
            serde_json::from_str(lines[0]).expect("Should be valid JSON");
        assert_eq!(json_obj["initial_domain"], "example.com");
    }

    #[tokio::test]
    async fn test_export_jsonl_filter_by_domain() {
        let temp_db = NamedTempFile::new().expect("Failed to create temp DB");
        let db_path = temp_db.path();

        let pool = SqlitePool::connect(&format!("sqlite:{}", db_path.display()))
            .await
            .expect("Failed to create database pool");
        run_migrations(&pool)
            .await
            .expect("Failed to run migrations");

        create_test_url_status(&pool, "example.com", 200).await;
        create_test_url_status(&pool, "other.com", 200).await;

        drop(pool);

        let temp_file = NamedTempFile::new().expect("Failed to create temp file");
        let output_path = temp_file.path().to_path_buf();

        let count = export_jsonl(&ExportOptions {
            db_path: db_path.to_path_buf(),
            output: Some(output_path.clone()),
            format: ExportFormat::Jsonl,
            run_id: None,
            domain: Some("example.com".to_string()),
            status: None,
            since: None,
            include_implied_tech: false,
        })
        .await
        .expect("Should export successfully");

        assert_eq!(count, 1, "Should export only 1 record matching domain");
    }

    #[tokio::test]
    async fn test_export_jsonl_filter_by_status() {
        let temp_db = NamedTempFile::new().expect("Failed to create temp DB");
        let db_path = temp_db.path();

        let pool = SqlitePool::connect(&format!("sqlite:{}", db_path.display()))
            .await
            .expect("Failed to create database pool");
        run_migrations(&pool)
            .await
            .expect("Failed to run migrations");

        create_test_url_status(&pool, "example.com", 200).await;
        create_test_url_status(&pool, "error.com", 404).await;

        drop(pool);

        let temp_file = NamedTempFile::new().expect("Failed to create temp file");
        let output_path = temp_file.path().to_path_buf();

        let count = export_jsonl(&ExportOptions {
            db_path: db_path.to_path_buf(),
            output: Some(output_path.clone()),
            format: ExportFormat::Jsonl,
            run_id: None,
            domain: None,
            status: Some(404),
            since: None,
            include_implied_tech: false,
        })
        .await
        .expect("Should export successfully");

        assert_eq!(count, 1, "Should export only 1 record matching status");
    }

    #[tokio::test]
    async fn test_export_jsonl_filter_by_since() {
        let temp_db = NamedTempFile::new().expect("Failed to create temp DB");
        let db_path = temp_db.path();

        let pool = SqlitePool::connect(&format!("sqlite:{}", db_path.display()))
            .await
            .expect("Failed to create database pool");
        run_migrations(&pool)
            .await
            .expect("Failed to run migrations");

        create_test_url_status(&pool, "example.com", 200).await;

        // Create a record with a later timestamp
        sqlx::query(
            "INSERT INTO url_status (
                initial_domain, final_domain, ip_address, http_status, http_status_text,
                response_time_seconds, title, observed_at_ms, run_id
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
            RETURNING id",
        )
        .bind("newer.com")
        .bind("newer.com")
        .bind("192.0.2.3")
        .bind(200)
        .bind("OK")
        .bind(1.5f64)
        .bind("Newer Page")
        .bind(1704153600000i64) // Later timestamp
        .bind("test-run-1")
        .fetch_one(&pool)
        .await
        .expect("Failed to insert");

        drop(pool);

        let temp_file = NamedTempFile::new().expect("Failed to create temp file");
        let output_path = temp_file.path().to_path_buf();

        // Filter by timestamp after the first record
        let count = export_jsonl(&ExportOptions {
            db_path: db_path.to_path_buf(),
            output: Some(output_path.clone()),
            format: ExportFormat::Jsonl,
            run_id: None,
            domain: None,
            status: None,
            since: Some(1704100000000i64), // Between the two timestamps
            include_implied_tech: false,
        })
        .await
        .expect("Should export successfully");

        assert_eq!(count, 1, "Should export only 1 record after timestamp");
    }

    #[tokio::test]
    async fn test_export_jsonl_with_technologies() {
        let temp_db = NamedTempFile::new().expect("Failed to create temp DB");
        let db_path = temp_db.path();

        let pool = SqlitePool::connect(&format!("sqlite:{}", db_path.display()))
            .await
            .expect("Failed to create database pool");
        run_migrations(&pool)
            .await
            .expect("Failed to run migrations");

        let url_id = create_test_url_status(&pool, "example.com", 200).await;

        // Add technologies
        sqlx::query(
            "INSERT INTO url_technologies (url_status_id, technology_name, technology_version)
             VALUES (?, ?, ?)",
        )
        .bind(url_id)
        .bind("WordPress")
        .bind(Some("6.8.3"))
        .execute(&pool)
        .await
        .expect("Failed to insert technology");

        sqlx::query(
            "INSERT INTO url_technologies (url_status_id, technology_name, technology_version)
             VALUES (?, ?, ?)",
        )
        .bind(url_id)
        .bind("PHP")
        .bind::<Option<String>>(None)
        .execute(&pool)
        .await
        .expect("Failed to insert technology");

        drop(pool);

        let temp_file = NamedTempFile::new().expect("Failed to create temp file");
        let output_path = temp_file.path().to_path_buf();

        let count = export_jsonl(&ExportOptions {
            db_path: db_path.to_path_buf(),
            output: Some(output_path.clone()),
            format: ExportFormat::Jsonl,
            run_id: None,
            domain: None,
            status: None,
            since: None,
            include_implied_tech: false,
        })
        .await
        .expect("Should export successfully");

        assert_eq!(count, 1);

        let mut file = std::fs::File::open(&output_path).expect("Failed to open output file");
        let mut contents = String::new();
        file.read_to_string(&mut contents)
            .expect("Failed to read output file");

        let json_obj: serde_json::Value =
            serde_json::from_str(contents.trim()).expect("Should be valid JSON");
        assert_eq!(json_obj["technology_count"], 2);
        let technologies = json_obj["technologies"]
            .as_array()
            .expect("Should be array");
        assert_eq!(technologies.len(), 2);
    }

    #[tokio::test]
    async fn test_export_jsonl_include_implied_tech_on_off() {
        let temp_db = NamedTempFile::new().expect("Failed to create temp DB");
        let db_path = temp_db.path();
        let pool = SqlitePool::connect(&format!("sqlite:{}", db_path.display()))
            .await
            .expect("Failed to create database pool");
        run_migrations(&pool)
            .await
            .expect("Failed to run migrations");
        let url_id = create_test_url_status(&pool, "implied.com", 200).await;
        sqlx::query(
            "INSERT INTO url_technologies (url_status_id, technology_name, is_implied)
             VALUES (?, ?, ?)",
        )
        .bind(url_id)
        .bind("nginx")
        .bind(0i64)
        .execute(&pool)
        .await
        .expect("insert observed tech");
        sqlx::query(
            "INSERT INTO url_technologies (url_status_id, technology_name, is_implied)
             VALUES (?, ?, ?)",
        )
        .bind(url_id)
        .bind("PHP")
        .bind(1i64)
        .execute(&pool)
        .await
        .expect("insert implied tech");
        drop(pool);

        let off_file = NamedTempFile::new().expect("Failed to create temp file");
        export_jsonl(&ExportOptions {
            db_path: db_path.to_path_buf(),
            output: Some(off_file.path().to_path_buf()),
            format: ExportFormat::Jsonl,
            run_id: None,
            domain: None,
            status: None,
            since: None,
            include_implied_tech: false,
        })
        .await
        .expect("export off");
        let off: serde_json::Value = serde_json::from_str(
            std::fs::read_to_string(off_file.path())
                .expect("read")
                .trim(),
        )
        .expect("json");
        let off_tech = off["technologies"].as_array().expect("array");
        assert_eq!(off["technology_count"], 1);
        assert_eq!(off_tech.len(), 1);
        assert_eq!(off_tech[0]["name"], "nginx");
        assert_eq!(off_tech[0]["is_implied"], false);

        let on_file = NamedTempFile::new().expect("Failed to create temp file");
        export_jsonl(&ExportOptions {
            db_path: db_path.to_path_buf(),
            output: Some(on_file.path().to_path_buf()),
            format: ExportFormat::Jsonl,
            run_id: None,
            domain: None,
            status: None,
            since: None,
            include_implied_tech: true,
        })
        .await
        .expect("export on");
        let on: serde_json::Value = serde_json::from_str(
            std::fs::read_to_string(on_file.path())
                .expect("read")
                .trim(),
        )
        .expect("json");
        let on_tech = on["technologies"].as_array().expect("array");
        assert_eq!(on["technology_count"], 2);
        assert_eq!(on_tech.len(), 2);
        let php = on_tech.iter().find(|t| t["name"] == "PHP").expect("PHP");
        assert_eq!(php["is_implied"], true);
        let nginx = on_tech
            .iter()
            .find(|t| t["name"] == "nginx")
            .expect("nginx");
        assert_eq!(nginx["is_implied"], false);
    }

    #[tokio::test]
    async fn test_export_jsonl_empty_database() {
        let temp_db = NamedTempFile::new().expect("Failed to create temp DB");
        let db_path = temp_db.path();

        let pool = SqlitePool::connect(&format!("sqlite:{}", db_path.display()))
            .await
            .expect("Failed to create database pool");
        run_migrations(&pool)
            .await
            .expect("Failed to run migrations");
        drop(pool);

        let temp_file = NamedTempFile::new().expect("Failed to create temp file");
        let output_path = temp_file.path().to_path_buf();

        let count = export_jsonl(&ExportOptions {
            db_path: db_path.to_path_buf(),
            output: Some(output_path.clone()),
            format: ExportFormat::Jsonl,
            run_id: None,
            domain: None,
            status: None,
            since: None,
            include_implied_tech: false,
        })
        .await
        .expect("Should export successfully even with empty database");

        assert_eq!(count, 0, "Should export 0 records from empty database");
    }

    #[tokio::test]
    async fn test_export_jsonl_with_redirect_chain() {
        let temp_db = NamedTempFile::new().expect("Failed to create temp DB");
        let db_path = temp_db.path();

        let pool = SqlitePool::connect(&format!("sqlite:{}", db_path.display()))
            .await
            .expect("Failed to create database pool");
        run_migrations(&pool)
            .await
            .expect("Failed to run migrations");

        let url_id = create_test_url_status(&pool, "example.com", 200).await;

        // Add redirect chain
        sqlx::query(
            "INSERT INTO url_redirect_chain (url_status_id, redirect_url, sequence_order)
             VALUES (?, ?, ?)",
        )
        .bind(url_id)
        .bind("http://example.com")
        .bind(0)
        .execute(&pool)
        .await
        .expect("Failed to insert redirect");

        sqlx::query(
            "INSERT INTO url_redirect_chain (url_status_id, redirect_url, sequence_order)
             VALUES (?, ?, ?)",
        )
        .bind(url_id)
        .bind("https://example.com")
        .bind(1)
        .execute(&pool)
        .await
        .expect("Failed to insert redirect");

        drop(pool);

        let temp_file = NamedTempFile::new().expect("Failed to create temp file");
        let output_path = temp_file.path().to_path_buf();

        let count = export_jsonl(&ExportOptions {
            db_path: db_path.to_path_buf(),
            output: Some(output_path.clone()),
            format: ExportFormat::Jsonl,
            run_id: None,
            domain: None,
            status: None,
            since: None,
            include_implied_tech: false,
        })
        .await
        .expect("Should export successfully");

        assert_eq!(count, 1);

        let mut file = std::fs::File::open(&output_path).expect("Failed to open output file");
        let mut contents = String::new();
        file.read_to_string(&mut contents)
            .expect("Failed to read output file");

        let json_obj: serde_json::Value =
            serde_json::from_str(contents.trim()).expect("Should be valid JSON");
        assert_eq!(json_obj["redirect_count"], 2);
        let redirect_chain = json_obj["redirect_chain"]
            .as_array()
            .expect("Should be array");
        assert_eq!(redirect_chain.len(), 2);
        assert_eq!(json_obj["final_redirect_url"], "https://example.com");
    }

    #[tokio::test]
    async fn test_export_jsonl_file_creation_error() {
        // Test error handling when file creation fails (e.g., invalid path)
        let temp_db = NamedTempFile::new().expect("Failed to create temp DB");
        let db_path = temp_db.path();

        let pool = SqlitePool::connect(&format!("sqlite:{}", db_path.display()))
            .await
            .expect("Failed to create database pool");
        run_migrations(&pool)
            .await
            .expect("Failed to run migrations");
        drop(pool);

        // Use an invalid path (directory instead of file)
        let invalid_path = std::path::PathBuf::from("/invalid/path/that/does/not/exist.jsonl");

        let result = export_jsonl(&ExportOptions {
            db_path: db_path.to_path_buf(),
            output: Some(invalid_path.clone()),
            format: ExportFormat::Jsonl,
            run_id: None,
            domain: None,
            status: None,
            since: None,
            include_implied_tech: false,
        })
        .await;

        // Should fail with file creation / path error (wording is OS-dependent)
        assert!(result.is_err(), "Should fail when file cannot be created");
        let error_msg = result.unwrap_err().to_string();
        assert!(
            error_msg.contains("Failed to create output file")
                || error_msg.contains("No such file")
                || error_msg.contains("Permission denied")
                || error_msg.contains("cannot find the path")
                || error_msg.contains("path specified"),
            "Error should mention file creation/path issue, got: {}",
            error_msg
        );
    }

    #[tokio::test]
    async fn test_export_jsonl_handles_malformed_technology_data() {
        // Test that malformed technology data (empty strings, special characters) is handled gracefully
        let temp_db = NamedTempFile::new().expect("Failed to create temp DB");
        let db_path = temp_db.path();

        let pool = SqlitePool::connect(&format!("sqlite:{}", db_path.display()))
            .await
            .expect("Failed to create database pool");
        run_migrations(&pool)
            .await
            .expect("Failed to run migrations");

        let url_id = create_test_url_status(&pool, "example.com", 200).await;

        // Add technology with empty version (should serialize as null)
        sqlx::query(
            "INSERT INTO url_technologies (url_status_id, technology_name, technology_version)
             VALUES (?, ?, ?)",
        )
        .bind(url_id)
        .bind("WordPress")
        .bind::<Option<String>>(None)
        .execute(&pool)
        .await
        .expect("Failed to insert technology");

        // Add technology with colon in name (tests key-value parsing)
        sqlx::query(
            "INSERT INTO url_technologies (url_status_id, technology_name, technology_version)
             VALUES (?, ?, ?)",
        )
        .bind(url_id)
        .bind("Tech:Name")
        .bind(Some("1.0"))
        .execute(&pool)
        .await
        .expect("Failed to insert technology");

        drop(pool);

        let temp_file = NamedTempFile::new().expect("Failed to create temp file");
        let output_path = temp_file.path().to_path_buf();

        let count = export_jsonl(&ExportOptions {
            db_path: db_path.to_path_buf(),
            output: Some(output_path.clone()),
            format: ExportFormat::Jsonl,
            run_id: None,
            domain: None,
            status: None,
            since: None,
            include_implied_tech: false,
        })
        .await
        .expect("Should export successfully");

        assert_eq!(count, 1);

        // Verify the export succeeded and JSON is valid
        let mut file = std::fs::File::open(&output_path).expect("Failed to open output file");
        let mut contents = String::new();
        file.read_to_string(&mut contents)
            .expect("Failed to read output file");

        let json_obj: serde_json::Value =
            serde_json::from_str(contents.trim()).expect("Should be valid JSON");
        let technologies = json_obj["technologies"]
            .as_array()
            .expect("Should be array");
        assert_eq!(technologies.len(), 2);
        let wordpress = technologies
            .iter()
            .find(|t| t["name"] == "WordPress")
            .expect("WordPress");
        assert!(wordpress["version"].is_null());
        let colon = technologies
            .iter()
            .find(|t| t["name"] == "Tech:Name")
            .expect("colon in technology name must round-trip");
        assert_eq!(colon["version"], "1.0");
    }

    #[tokio::test]
    async fn test_export_jsonl_handles_empty_redirect_chain() {
        // Test that empty redirect chain is handled correctly
        let temp_db = NamedTempFile::new().expect("Failed to create temp DB");
        let db_path = temp_db.path();

        let pool = SqlitePool::connect(&format!("sqlite:{}", db_path.display()))
            .await
            .expect("Failed to create database pool");
        run_migrations(&pool)
            .await
            .expect("Failed to run migrations");

        let _url_id = create_test_url_status(&pool, "example.com", 200).await;
        // Don't add any redirect chain entries

        drop(pool);

        let temp_file = NamedTempFile::new().expect("Failed to create temp file");
        let output_path = temp_file.path().to_path_buf();

        let count = export_jsonl(&ExportOptions {
            db_path: db_path.to_path_buf(),
            output: Some(output_path.clone()),
            format: ExportFormat::Jsonl,
            run_id: None,
            domain: None,
            status: None,
            since: None,
            include_implied_tech: false,
        })
        .await
        .expect("Should export successfully");

        assert_eq!(count, 1);

        let mut file = std::fs::File::open(&output_path).expect("Failed to open output file");
        let mut contents = String::new();
        file.read_to_string(&mut contents)
            .expect("Failed to read output file");

        let json_obj: serde_json::Value =
            serde_json::from_str(contents.trim()).expect("Should be valid JSON");
        assert_eq!(json_obj["redirect_count"], 0);
        let redirect_chain = json_obj["redirect_chain"]
            .as_array()
            .expect("Should be array");
        assert!(redirect_chain.is_empty());
        assert_eq!(json_obj["final_redirect_url"], "");
    }

    /// Contract: `body_truncated` (scan-completeness signal from migration
    /// `0009_secrets_scan_completeness.sql`) must be surfaced as a named JSONL field.
    #[tokio::test]
    async fn test_export_jsonl_body_truncated_field_present() {
        let temp_db = NamedTempFile::new().expect("Failed to create temp DB");
        let db_path = temp_db.path();

        let pool = SqlitePool::connect(&format!("sqlite:{}", db_path.display()))
            .await
            .expect("Failed to create database pool");
        run_migrations(&pool)
            .await
            .expect("Failed to run migrations");

        let url_id = create_test_url_status(&pool, "truncated.example", 200).await;
        sqlx::query("UPDATE url_status SET body_truncated = 1 WHERE id = ?")
            .bind(url_id)
            .execute(&pool)
            .await
            .expect("Failed to set body_truncated");

        drop(pool);

        let temp_file = NamedTempFile::new().expect("Failed to create temp file");
        let output_path = temp_file.path().to_path_buf();

        let count = export_jsonl(&ExportOptions {
            db_path: db_path.to_path_buf(),
            output: Some(output_path.clone()),
            format: ExportFormat::Jsonl,
            run_id: None,
            domain: None,
            status: None,
            since: None,
            include_implied_tech: false,
        })
        .await
        .expect("Should export successfully");
        assert_eq!(count, 1);

        let mut file = std::fs::File::open(&output_path).expect("Failed to open output file");
        let mut contents = String::new();
        file.read_to_string(&mut contents)
            .expect("Failed to read output file");

        let json_obj: serde_json::Value =
            serde_json::from_str(contents.trim()).expect("Should be valid JSON");
        assert_eq!(json_obj["body_truncated"], true);
    }

    #[tokio::test]
    async fn test_export_jsonl_handles_null_values() {
        // Test that NULL values in database are handled correctly (serialized as null in JSON)
        // This is critical - prevents panics from NULL database values
        let temp_db = NamedTempFile::new().expect("Failed to create temp DB");
        let db_path = temp_db.path();

        let pool = SqlitePool::connect(&format!("sqlite:{}", db_path.display()))
            .await
            .expect("Failed to create database pool");
        run_migrations(&pool)
            .await
            .expect("Failed to run migrations");

        // Create record with NULL values for optional fields
        create_test_run(&pool, "test-run-1").await;

        sqlx::query(
            "INSERT INTO url_status (
                initial_domain, final_domain, ip_address, http_status, http_status_text,
                response_time_seconds, title, observed_at_ms, run_id,
                reverse_dns_name, description, tls_version, ssl_cert_subject,
                ssl_cert_issuer, ssl_cert_valid_to_ms, cipher_suite, key_algorithm,
                spf_record, dmarc_record
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
        )
        .bind("example.com")
        .bind("example.com")
        .bind("192.0.2.1")
        .bind(200)
        .bind("OK")
        .bind(1.5f64)
        .bind("Test Page")
        .bind(1704067200000i64)
        .bind("test-run-1")
        .bind::<Option<String>>(None) // NULL reverse_dns
        .bind::<Option<String>>(None) // NULL description
        .bind::<Option<String>>(None) // NULL tls_version
        .bind::<Option<String>>(None) // NULL ssl_cert_subject
        .bind::<Option<String>>(None) // NULL ssl_cert_issuer
        .bind::<Option<i64>>(None) // NULL ssl_cert_valid_to_ms
        .bind::<Option<String>>(None) // NULL cipher_suite
        .bind::<Option<String>>(None) // NULL key_algorithm
        .bind::<Option<String>>(None) // NULL spf_record
        .bind::<Option<String>>(None) // NULL dmarc_record
        .execute(&pool)
        .await
        .expect("Failed to insert");

        drop(pool);

        let temp_file = NamedTempFile::new().expect("Failed to create temp file");
        let output_path = temp_file.path().to_path_buf();

        let count = export_jsonl(&ExportOptions {
            db_path: db_path.to_path_buf(),
            output: Some(output_path.clone()),
            format: ExportFormat::Jsonl,
            run_id: None,
            domain: None,
            status: None,
            since: None,
            include_implied_tech: false,
        })
        .await
        .expect("Should export successfully even with NULL values");

        assert_eq!(count, 1);

        let mut file = std::fs::File::open(&output_path).expect("Failed to open output file");
        let mut contents = String::new();
        file.read_to_string(&mut contents)
            .expect("Failed to read output file");

        let json_obj: serde_json::Value =
            serde_json::from_str(contents.trim()).expect("Should be valid JSON");
        // NULL values should be serialized as null in JSON
        assert_eq!(json_obj["reverse_dns"], serde_json::Value::Null);
        assert_eq!(json_obj["description"], serde_json::Value::Null);
    }

    #[tokio::test]
    async fn test_export_jsonl_handles_technology_with_colon_in_name() {
        // Test that technologies with colons in names are handled correctly
        // This is critical - technology names like "Tech:Name" could break parsing
        // The code at line 156 splits on ':' which could break if name contains colon
        let temp_db = NamedTempFile::new().expect("Failed to create temp DB");
        let db_path = temp_db.path();

        let pool = SqlitePool::connect(&format!("sqlite:{}", db_path.display()))
            .await
            .expect("Failed to create database pool");
        run_migrations(&pool)
            .await
            .expect("Failed to run migrations");

        let url_id = create_test_url_status(&pool, "example.com", 200).await;

        // Add technology with colon in name (tests parsing logic)
        sqlx::query(
            "INSERT INTO url_technologies (url_status_id, technology_name, technology_version)
             VALUES (?, ?, ?)",
        )
        .bind(url_id)
        .bind("Tech:Name") // Colon in name
        .bind(Some("1.0"))
        .execute(&pool)
        .await
        .expect("Failed to insert");

        drop(pool);

        let temp_file = NamedTempFile::new().expect("Failed to create temp file");
        let output_path = temp_file.path().to_path_buf();

        let count = export_jsonl(&ExportOptions {
            db_path: db_path.to_path_buf(),
            output: Some(output_path.clone()),
            format: ExportFormat::Jsonl,
            run_id: None,
            domain: None,
            status: None,
            since: None,
            include_implied_tech: false,
        })
        .await
        .expect("Should export successfully");

        assert_eq!(count, 1);

        let contents = std::fs::read_to_string(&output_path).expect("Failed to read output file");
        let json_obj: serde_json::Value =
            serde_json::from_str(contents.trim()).expect("Should be valid JSON");
        let technologies = json_obj["technologies"]
            .as_array()
            .expect("Should be array");
        assert_eq!(technologies.len(), 1);
        assert_eq!(technologies[0]["name"], "Tech:Name");
        assert_eq!(technologies[0]["version"], "1.0");
    }

    async fn insert_dns_data(pool: &SqlitePool, url_id: i64) {
        for ns in &["ns1.example.com", "ns2.example.com"] {
            sqlx::query("INSERT INTO url_nameservers (url_status_id, nameserver) VALUES (?, ?)")
                .bind(url_id)
                .bind(ns)
                .execute(pool)
                .await
                .expect("insert nameserver");
        }
        for (rtype, val) in &[
            ("SPF", "v=spf1 include:_spf.google.com ~all"),
            ("DMARC", "v=DMARC1; p=reject; rua=mailto:dmarc@example.com"),
        ] {
            sqlx::query("INSERT INTO url_txt_records (url_status_id, record_type, record_value) VALUES (?, ?, ?)")
                .bind(url_id).bind(rtype).bind(val)
                .execute(pool).await.expect("insert txt");
        }
        for (pri, mx) in &[(10, "mail.example.com"), (20, "mail2.example.com")] {
            sqlx::query("INSERT INTO url_mx_records (url_status_id, priority, mail_exchange) VALUES (?, ?, ?)")
                .bind(url_id).bind(pri).bind(mx)
                .execute(pool).await.expect("insert mx");
        }
    }

    async fn insert_social_and_structured_data(pool: &SqlitePool, url_id: i64) {
        for (dtype, prop, val) in &[
            ("open_graph", "og:title", "Example Page"),
            ("json_ld", "@type", "Organization"),
        ] {
            sqlx::query("INSERT INTO url_structured_data (url_status_id, data_type, property_name, property_value) VALUES (?, ?, ?, ?)")
                .bind(url_id).bind(dtype).bind(prop).bind(val)
                .execute(pool).await.expect("insert structured data");
        }
        sqlx::query("INSERT INTO url_social_media_links (url_status_id, platform, profile_url, identifier) VALUES (?, ?, ?, ?)")
            .bind(url_id).bind("LinkedIn").bind("https://linkedin.com/company/example").bind("example")
            .execute(pool).await.expect("insert social");
        sqlx::query("INSERT INTO url_social_media_links (url_status_id, platform, profile_url, identifier) VALUES (?, ?, ?, ?)")
            .bind(url_id).bind("Twitter").bind("https://twitter.com/example").bind::<Option<&str>>(None)
            .execute(pool).await.expect("insert social");
    }

    async fn insert_headers_and_failures(pool: &SqlitePool, url_id: i64) {
        sqlx::query("INSERT INTO url_partial_failures (url_status_id, error_type, error_message, observed_at_ms, run_id) VALUES (?, ?, ?, ?, ?)")
            .bind(url_id).bind("DNS NS lookup error").bind("Timeout resolving NS records for example.com")
            .bind(1704067200000i64).bind("test-run-1")
            .execute(pool).await.expect("insert partial failure");
        for (name, value) in &[
            ("Content-Type", "text/html; charset=utf-8"),
            ("Server", "nginx/1.24"),
            ("X-Custom-Header", "custom-value"),
        ] {
            sqlx::query("INSERT INTO url_http_headers (url_status_id, header_name, header_value) VALUES (?, ?, ?)")
                .bind(url_id).bind(name).bind(value)
                .execute(pool).await.expect("insert http header");
        }
        sqlx::query("INSERT INTO url_security_headers (url_status_id, header_name, header_value) VALUES (?, ?, ?)")
            .bind(url_id).bind("Strict-Transport-Security").bind("max-age=31536000; includeSubDomains")
            .execute(pool).await.expect("insert security header");
    }

    /// Helper to set up a fully-populated test database with all satellite data.
    async fn create_fully_populated_db() -> (NamedTempFile, i64) {
        let temp_db = NamedTempFile::new().expect("Failed to create temp DB");
        let pool = SqlitePool::connect(&format!("sqlite:{}", temp_db.path().display()))
            .await
            .expect("Failed to create database pool");
        run_migrations(&pool)
            .await
            .expect("Failed to run migrations");

        let url_id = create_test_url_status(&pool, "example.com", 200).await;
        insert_dns_data(&pool, url_id).await;
        insert_social_and_structured_data(&pool, url_id).await;
        insert_headers_and_failures(&pool, url_id).await;

        drop(pool);
        (temp_db, url_id)
    }

    #[tokio::test]
    async fn test_export_jsonl_all_satellite_data() {
        // Single comprehensive test: one DB setup, one export, all assertions.
        // Validates DNS records, social media identifiers, partial failures,
        // structured data entries, and unfiltered headers in a single pass.
        let (temp_db, _url_id) = create_fully_populated_db().await;

        let temp_file = NamedTempFile::new().expect("Failed to create temp file");
        let output_path = temp_file.path().to_path_buf();

        let count = export_jsonl(&ExportOptions {
            db_path: temp_db.path().to_path_buf(),
            output: Some(output_path.clone()),
            format: ExportFormat::Jsonl,
            run_id: None,
            domain: None,
            status: None,
            since: None,
            include_implied_tech: false,
        })
        .await
        .expect("Should export successfully");
        assert_eq!(count, 1);

        let contents = std::fs::read_to_string(&output_path).expect("Failed to read output");
        let j: serde_json::Value =
            serde_json::from_str(contents.trim()).expect("Should be valid JSON");

        // --- DNS: nameservers are actual strings, not just a count ---
        let dns = &j["dns"];
        let nameservers = dns["nameservers"].as_array().expect("array");
        assert_eq!(nameservers.len(), 2);
        assert!(nameservers.contains(&serde_json::json!("ns1.example.com")));
        assert!(nameservers.contains(&serde_json::json!("ns2.example.com")));

        // --- DNS: TXT records have type + content ---
        let txt = dns["txt_records"].as_array().expect("array");
        assert_eq!(txt.len(), 2);
        let spf = txt.iter().find(|r| r["record_type"] == "SPF").expect("SPF");
        assert!(spf["content"].as_str().unwrap().contains("v=spf1"));

        // --- DNS: MX records have priority + mail_exchange ---
        let mx = dns["mx_records"].as_array().expect("array");
        assert_eq!(mx.len(), 2);
        assert_eq!(mx[0]["priority"], 10);
        assert_eq!(mx[0]["mail_exchange"], "mail.example.com");

        // --- Social media: identifier present when extracted, null otherwise ---
        let social = j["social_media_links"].as_array().expect("array");
        assert_eq!(social.len(), 2);
        let linkedin = social
            .iter()
            .find(|s| s["platform"] == "LinkedIn")
            .expect("LinkedIn");
        assert_eq!(linkedin["identifier"], "example");
        assert_eq!(linkedin["url"], "https://linkedin.com/company/example");
        let twitter = social
            .iter()
            .find(|s| s["platform"] == "Twitter")
            .expect("Twitter");
        assert!(twitter["identifier"].is_null());

        // --- Partial failures: error_type + error_message ---
        let failures = j["partial_failures"].as_array().expect("array");
        assert_eq!(failures.len(), 1);
        assert_eq!(failures[0]["error_type"], "DNS NS lookup error");
        assert!(failures[0]["error_message"]
            .as_str()
            .unwrap()
            .contains("Timeout"));

        // --- Structured data: entries with data_type, property_name, property_value ---
        let entries = j["structured_data"]["entries"].as_array().expect("array");
        assert_eq!(entries.len(), 2);
        let og = entries
            .iter()
            .find(|e| e["data_type"] == "open_graph")
            .expect("og");
        assert_eq!(og["property_name"], "og:title");
        assert_eq!(og["property_value"], "Example Page");

        // --- HTTP headers: unfiltered (all 3, including custom) ---
        let headers = j["http_headers"].as_array().expect("array");
        assert_eq!(
            headers.len(),
            3,
            "Should include ALL headers, not just whitelisted"
        );
        let custom = headers
            .iter()
            .find(|h| h["name"] == "X-Custom-Header")
            .expect("custom");
        assert_eq!(custom["value"], "custom-value");

        // --- Security headers ---
        let sec = j["security_headers"].as_array().expect("array");
        assert_eq!(sec.len(), 1);
        assert_eq!(sec[0]["name"], "Strict-Transport-Security");
    }

    #[tokio::test]
    async fn test_export_jsonl_empty_satellite_tables() {
        // Verify that when no satellite data exists, arrays are empty (not errors)
        let temp_db = NamedTempFile::new().expect("Failed to create temp DB");
        let db_path = temp_db.path();

        let pool = SqlitePool::connect(&format!("sqlite:{}", db_path.display()))
            .await
            .expect("Failed to create database pool");
        run_migrations(&pool)
            .await
            .expect("Failed to run migrations");

        // Create URL with no satellite data at all
        let _url_id = create_test_url_status(&pool, "bare.example.com", 200).await;
        drop(pool);

        let temp_file = NamedTempFile::new().expect("Failed to create temp file");
        let output_path = temp_file.path().to_path_buf();

        export_jsonl(&ExportOptions {
            db_path: db_path.to_path_buf(),
            output: Some(output_path.clone()),
            format: ExportFormat::Jsonl,
            run_id: None,
            domain: None,
            status: None,
            since: None,
            include_implied_tech: false,
        })
        .await
        .expect("Should export successfully even with empty satellites");

        let contents = std::fs::read_to_string(&output_path).expect("Failed to read output");
        let json_obj: serde_json::Value =
            serde_json::from_str(contents.trim()).expect("Should be valid JSON");

        // All arrays should be empty, not missing
        assert_eq!(json_obj["dns"]["nameservers"].as_array().unwrap().len(), 0);
        assert_eq!(json_obj["dns"]["txt_records"].as_array().unwrap().len(), 0);
        assert_eq!(json_obj["dns"]["mx_records"].as_array().unwrap().len(), 0);
        assert_eq!(
            json_obj["structured_data"]["entries"]
                .as_array()
                .unwrap()
                .len(),
            0
        );
        assert_eq!(json_obj["partial_failures"].as_array().unwrap().len(), 0);
        assert_eq!(json_obj["http_headers"].as_array().unwrap().len(), 0);
        assert_eq!(json_obj["security_headers"].as_array().unwrap().len(), 0);
    }
}