mockforge-bench 0.3.135

Load and performance testing for MockForge
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
//! k6 script generation for load testing real endpoints

use crate::dynamic_params::{DynamicParamProcessor, DynamicPlaceholder};
use crate::error::{BenchError, Result};
use crate::request_gen::RequestTemplate;
use crate::scenarios::LoadScenario;
use handlebars::Handlebars;
use serde::Serialize;
#[cfg(test)]
use serde_json::json;
use serde_json::Value;
use std::collections::{HashMap, HashSet};

/// Typed template data for `k6_script.hbs`.
///
/// Every field referenced by `{{variable}}` or `{{#if flag}}` in the template
/// is a required field here, so the compiler prevents the Issue-#79 class of
/// bugs (template rendered with missing data).
#[derive(Debug, Clone, Serialize)]
pub struct K6ScriptTemplateData {
    pub base_url: String,
    pub stages: Vec<K6StageData>,
    pub operations: Vec<K6OperationData>,
    pub threshold_percentile: String,
    pub threshold_ms: u64,
    pub max_error_rate: f64,
    pub scenario_name: String,
    pub skip_tls_verify: bool,
    pub has_dynamic_values: bool,
    pub dynamic_imports: Vec<String>,
    pub dynamic_globals: Vec<String>,
    pub security_testing_enabled: bool,
    pub has_custom_headers: bool,
    /// When true, emit `Transfer-Encoding: chunked` on every request that has a
    /// body. NOTE: k6 runs on Go's `net/http`, which decides chunking based on
    /// the body type — a string body has a known length and Go will normally
    /// send `Content-Length`. Setting this header explicitly is the closest
    /// k6-script-level approximation; for true raw chunked traffic, prefer
    /// `curl --data-binary @file -H "Transfer-Encoding: chunked"` or a custom
    /// hyper/reqwest harness.
    pub chunked_request_bodies: bool,
    /// Optional target RPS. When `Some(n)`, the script switches the executor
    /// from `ramping-vus` to `constant-arrival-rate` at `n` requests/sec.
    /// Issue #79.
    pub target_rps: Option<u32>,
    /// When true, the generated script sets `noConnectionReuse: true` on every
    /// request so each one opens a fresh TCP/TLS connection. Used to drive
    /// connections-per-second load. Issue #79.
    pub no_keep_alive: bool,
    /// Total test duration in seconds. Used by the `constant-arrival-rate`
    /// executor (when `target_rps` is set) which needs a single duration
    /// rather than a list of stages. Issue #79 — Srikanth's round-5 reply:
    /// `--rps` was previously deriving duration from the last stage of the
    /// chosen scenario; under `ramp-up` (the default) the last stage has
    /// `target: 0`, which gave `preAllocatedVUs: 0` and 0 requests.
    pub duration_secs: u64,
    /// Max VUs to pre-allocate for the `constant-arrival-rate` executor.
    /// Issue #79 (round 5).
    pub max_vus: u32,
}

/// Typed template data for `k6_crud_flow.hbs`.
#[derive(Debug, Clone, Serialize)]
pub struct K6CrudFlowTemplateData {
    pub base_url: String,
    pub flows: Vec<Value>,
    pub extract_fields: Vec<String>,
    pub duration_secs: u64,
    pub max_vus: u32,
    pub auth_header: Option<String>,
    pub custom_headers: HashMap<String, String>,
    pub skip_tls_verify: bool,
    pub stages: Vec<K6StageData>,
    pub threshold_percentile: String,
    pub threshold_ms: u64,
    pub max_error_rate: f64,
    /// Raw JSON string for embedding in k6 script (rendered unescaped via `{{{headers}}}`)
    pub headers: String,
    pub dynamic_imports: Vec<String>,
    pub dynamic_globals: Vec<String>,
    pub extracted_values_output_path: String,
    pub error_injection_enabled: bool,
    pub error_rate: f64,
    pub error_types: Vec<String>,
    pub security_testing_enabled: bool,
    pub has_custom_headers: bool,
}

/// A k6 load stage for template rendering.
#[derive(Debug, Clone, Serialize)]
pub struct K6StageData {
    pub duration: String,
    pub target: u32,
}

/// Per-operation data for the `k6_script.hbs` template.
#[derive(Debug, Clone, Serialize)]
pub struct K6OperationData {
    pub index: usize,
    pub name: String,
    pub metric_name: String,
    pub display_name: String,
    pub method: String,
    pub path: Value,
    pub path_is_dynamic: bool,
    pub headers: Value,
    pub body: Option<Value>,
    pub body_is_dynamic: bool,
    pub has_body: bool,
    pub is_get_or_head: bool,
}

/// Configuration for k6 script generation
pub struct K6Config {
    pub target_url: String,
    /// API base path prefix (e.g., "/api" or "/v2")
    /// Prepended to all API endpoint paths
    pub base_path: Option<String>,
    pub scenario: LoadScenario,
    pub duration_secs: u64,
    pub max_vus: u32,
    pub threshold_percentile: String,
    pub threshold_ms: u64,
    pub max_error_rate: f64,
    pub auth_header: Option<String>,
    pub custom_headers: HashMap<String, String>,
    pub skip_tls_verify: bool,
    pub security_testing_enabled: bool,
    /// Emit `Transfer-Encoding: chunked` on every request body. See
    /// `K6ScriptTemplateData::chunked_request_bodies` for caveats.
    pub chunked_request_bodies: bool,
    /// Target RPS for `constant-arrival-rate` executor. `None` falls back to
    /// the legacy ramping-vus executor.
    pub target_rps: Option<u32>,
    /// When true, set `noConnectionReuse: true` on every request so each one
    /// opens a fresh TCP/TLS connection (drives high CPS).
    pub no_keep_alive: bool,
}

/// Generate k6 load test script
pub struct K6ScriptGenerator {
    config: K6Config,
    templates: Vec<RequestTemplate>,
}

impl K6ScriptGenerator {
    /// Create a new k6 script generator
    pub fn new(config: K6Config, templates: Vec<RequestTemplate>) -> Self {
        Self { config, templates }
    }

    /// Generate the k6 script
    pub fn generate(&self) -> Result<String> {
        let handlebars = Handlebars::new();

        let template = include_str!("templates/k6_script.hbs");

        let data = self.build_template_data()?;

        let value = serde_json::to_value(&data)
            .map_err(|e| BenchError::ScriptGenerationFailed(e.to_string()))?;

        handlebars
            .render_template(template, &value)
            .map_err(|e| BenchError::ScriptGenerationFailed(e.to_string()))
    }

    /// Maximum length for a k6 metric name *base* (the part before any
    /// `_latency` / `_errors` / `_step{N}_*` suffix). k6 enforces a
    /// 128-char limit on the full metric name; the longest suffix used by
    /// our templates is `_step99_errors` (15 chars), so we cap the base at
    /// 128 - 16 = 112 to be safe.
    const K6_METRIC_NAME_BASE_MAX_LEN: usize = 112;

    /// Sanitize a name into a valid k6 metric-name base, capped at
    /// `K6_METRIC_NAME_BASE_MAX_LEN` characters.
    ///
    /// k6 rejects metric names longer than 128 chars, and our templates
    /// append suffixes like `_latency`, `_errors`, `_stepN_latency` —
    /// reserve room for the longest suffix and truncate the base name
    /// when needed. Truncation appends an 8-hex-char hash of the original
    /// name so distinct long names produce distinct metric names.
    ///
    /// Examples:
    /// - "short_name" -> "short_name"
    /// - 200-char OperationId -> "<first-103-chars>_<8-hex-hash>"
    pub fn sanitize_k6_metric_name(name: &str) -> String {
        let sanitized = Self::sanitize_js_identifier(name);
        if sanitized.len() <= Self::K6_METRIC_NAME_BASE_MAX_LEN {
            return sanitized;
        }

        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};
        let mut hasher = DefaultHasher::new();
        // Hash the original name (not the sanitized one) so two distinct
        // sources that sanitize to the same string still get different
        // hashes when they exceed the limit.
        name.hash(&mut hasher);
        let hash_suffix = format!("{:08x}", hasher.finish() as u32);

        // Reserve `_<8-hex>` = 9 chars at the end.
        let prefix_len = Self::K6_METRIC_NAME_BASE_MAX_LEN - 9;
        let prefix = &sanitized[..prefix_len];
        // Strip a trailing underscore on the prefix so we don't end up with `__hash`.
        let prefix = prefix.trim_end_matches('_');
        format!("{}_{}", prefix, hash_suffix)
    }

    /// Sanitize a name to be a valid JavaScript identifier
    ///
    /// Replaces invalid characters (dots, spaces, special chars) with underscores.
    /// Ensures the identifier starts with a letter or underscore (not a number).
    ///
    /// Examples:
    /// - "billing.subscriptions.v1" -> "billing_subscriptions_v1"
    /// - "get user" -> "get_user"
    /// - "123invalid" -> "_123invalid"
    pub fn sanitize_js_identifier(name: &str) -> String {
        let mut result = String::new();
        let mut chars = name.chars().peekable();

        // Ensure it starts with a letter or underscore (not a number)
        if let Some(&first) = chars.peek() {
            if first.is_ascii_digit() {
                result.push('_');
            }
        }

        for ch in chars {
            if ch.is_ascii_alphanumeric() || ch == '_' {
                result.push(ch);
            } else {
                // Replace invalid characters with underscore
                // Avoid consecutive underscores
                if !result.ends_with('_') {
                    result.push('_');
                }
            }
        }

        // Remove trailing underscores
        result = result.trim_end_matches('_').to_string();

        // If empty after sanitization, use a default name
        if result.is_empty() {
            result = "operation".to_string();
        }

        result
    }

    /// Build the typed template data for rendering.
    fn build_template_data(&self) -> Result<K6ScriptTemplateData> {
        let stages = self
            .config
            .scenario
            .generate_stages(self.config.duration_secs, self.config.max_vus);

        // Get the base path (defaults to empty string if not set)
        let base_path = self.config.base_path.as_deref().unwrap_or("");

        // Track all placeholders used across all operations
        let mut all_placeholders: HashSet<DynamicPlaceholder> = HashSet::new();

        let operations = self
            .templates
            .iter()
            .enumerate()
            .map(|(idx, template)| {
                let display_name = template.operation.display_name();
                let sanitized_name = Self::sanitize_js_identifier(&display_name);
                // metric_name must satisfy k6's 128-char limit AND leave room
                // for suffixes like `_latency` / `_errors` / `_stepN_*`.
                // Long deeply-nested operationIds (e.g. Microsoft Graph) exceed
                // this; sanitize_k6_metric_name truncates with a hash suffix
                // for uniqueness. (See issue #79 — Srikanth's microsoft-graph.yaml run.)
                let metric_name = Self::sanitize_k6_metric_name(&display_name);
                // k6 uses 'del' instead of 'delete' for HTTP DELETE method
                let k6_method = match template.operation.method.to_lowercase().as_str() {
                    "delete" => "del".to_string(),
                    m => m.to_string(),
                };
                // GET and HEAD methods only take 2 arguments in k6: http.get(url, params)
                // Other methods take 3 arguments: http.post(url, body, params)
                let is_get_or_head = matches!(k6_method.as_str(), "get" | "head");

                // Process path for dynamic placeholders
                // Prepend base_path if configured
                let raw_path = template.generate_path();
                let full_path = if base_path.is_empty() {
                    raw_path
                } else {
                    format!("{}{}", base_path, raw_path)
                };
                let processed_path = DynamicParamProcessor::process_path(&full_path);
                all_placeholders.extend(processed_path.placeholders.clone());

                // Process body for dynamic placeholders
                let (body_value, body_is_dynamic) = if let Some(body) = &template.body {
                    let processed_body = DynamicParamProcessor::process_json_body(body);
                    all_placeholders.extend(processed_body.placeholders.clone());
                    (Some(processed_body.value), processed_body.is_dynamic)
                } else {
                    (None, false)
                };

                let path_value = if processed_path.is_dynamic {
                    processed_path.value
                } else {
                    full_path
                };

                K6OperationData {
                    index: idx,
                    name: sanitized_name,
                    metric_name,
                    display_name,
                    method: k6_method,
                    path: Value::String(path_value),
                    path_is_dynamic: processed_path.is_dynamic,
                    headers: Value::String(self.build_headers_json(template)),
                    body: body_value.map(Value::String),
                    body_is_dynamic,
                    has_body: template.body.is_some(),
                    is_get_or_head,
                }
            })
            .collect::<Vec<_>>();

        // Get required imports and global initializations based on placeholders used
        let required_imports: Vec<String> =
            DynamicParamProcessor::get_required_imports(&all_placeholders)
                .into_iter()
                .map(String::from)
                .collect();
        let required_globals: Vec<String> =
            DynamicParamProcessor::get_required_globals(&all_placeholders)
                .into_iter()
                .map(String::from)
                .collect();
        let has_dynamic_values = !all_placeholders.is_empty();

        Ok(K6ScriptTemplateData {
            base_url: self.config.target_url.clone(),
            stages: stages
                .iter()
                .map(|s| K6StageData {
                    duration: s.duration.clone(),
                    target: s.target,
                })
                .collect(),
            operations,
            threshold_percentile: self.config.threshold_percentile.clone(),
            threshold_ms: self.config.threshold_ms,
            max_error_rate: self.config.max_error_rate,
            scenario_name: format!("{:?}", self.config.scenario).to_lowercase(),
            skip_tls_verify: self.config.skip_tls_verify,
            has_dynamic_values,
            dynamic_imports: required_imports,
            dynamic_globals: required_globals,
            security_testing_enabled: self.config.security_testing_enabled,
            has_custom_headers: !self.config.custom_headers.is_empty(),
            chunked_request_bodies: self.config.chunked_request_bodies,
            target_rps: self.config.target_rps,
            no_keep_alive: self.config.no_keep_alive,
            duration_secs: self.config.duration_secs,
            max_vus: self.config.max_vus,
        })
    }

    /// Build headers for a request template as a JSON string for k6 script
    fn build_headers_json(&self, template: &RequestTemplate) -> String {
        let mut headers = template.get_headers();

        // Add auth header if provided
        if let Some(auth) = &self.config.auth_header {
            headers.insert("Authorization".to_string(), auth.clone());
        }

        // Add custom headers
        for (key, value) in &self.config.custom_headers {
            headers.insert(key.clone(), value.clone());
        }

        // Force chunked transfer encoding when requested. Only meaningful for
        // requests with bodies (POST/PUT/PATCH); k6/Go may still send
        // Content-Length in some cases — see the doc on
        // `K6ScriptTemplateData::chunked_request_bodies`.
        if self.config.chunked_request_bodies && template.body.is_some() {
            headers.insert("Transfer-Encoding".to_string(), "chunked".to_string());
        }

        // Convert to JSON string for embedding in k6 script
        serde_json::to_string(&headers).unwrap_or_else(|_| "{}".to_string())
    }

    /// Validate the generated k6 script for common issues
    ///
    /// Checks for:
    /// - Invalid metric names (contains dots or special characters)
    /// - Invalid JavaScript variable names
    /// - Missing required k6 imports
    ///
    /// Returns a list of validation errors, empty if all checks pass.
    pub fn validate_script(script: &str) -> Vec<String> {
        let mut errors = Vec::new();

        // Check for required k6 imports
        if !script.contains("import http from 'k6/http'") {
            errors.push("Missing required import: 'k6/http'".to_string());
        }
        if !script.contains("import { check") && !script.contains("import {check") {
            errors.push("Missing required import: 'check' from 'k6'".to_string());
        }
        if !script.contains("import { Rate, Trend") && !script.contains("import {Rate, Trend") {
            errors.push("Missing required import: 'Rate, Trend' from 'k6/metrics'".to_string());
        }

        // Check for invalid metric names in Trend/Rate constructors
        // k6 metric names must only contain ASCII letters, numbers, or underscores
        // and start with a letter or underscore
        let lines: Vec<&str> = script.lines().collect();
        for (line_num, line) in lines.iter().enumerate() {
            let trimmed = line.trim();

            // Check for Trend/Rate constructors with invalid metric names
            if trimmed.contains("new Trend(") || trimmed.contains("new Rate(") {
                // Extract the metric name from the string literal
                // Pattern: new Trend('metric_name') or new Rate("metric_name")
                if let Some(start) = trimmed.find('\'') {
                    if let Some(end) = trimmed[start + 1..].find('\'') {
                        let metric_name = &trimmed[start + 1..start + 1 + end];
                        if !Self::is_valid_k6_metric_name(metric_name) {
                            errors.push(format!(
                                "Line {}: Invalid k6 metric name '{}'. Metric names must only contain ASCII letters, numbers, or underscores and start with a letter or underscore.",
                                line_num + 1,
                                metric_name
                            ));
                        }
                    }
                } else if let Some(start) = trimmed.find('"') {
                    if let Some(end) = trimmed[start + 1..].find('"') {
                        let metric_name = &trimmed[start + 1..start + 1 + end];
                        if !Self::is_valid_k6_metric_name(metric_name) {
                            errors.push(format!(
                                "Line {}: Invalid k6 metric name '{}'. Metric names must only contain ASCII letters, numbers, or underscores and start with a letter or underscore.",
                                line_num + 1,
                                metric_name
                            ));
                        }
                    }
                }
            }

            // Check for invalid JavaScript variable names (containing dots)
            if trimmed.starts_with("const ") || trimmed.starts_with("let ") {
                if let Some(equals_pos) = trimmed.find('=') {
                    let var_decl = &trimmed[..equals_pos];
                    // Check if variable name contains a dot (invalid identifier)
                    // But exclude string literals
                    if var_decl.contains('.')
                        && !var_decl.contains("'")
                        && !var_decl.contains("\"")
                        && !var_decl.trim().starts_with("//")
                    {
                        errors.push(format!(
                            "Line {}: Invalid JavaScript variable name with dot: {}. Variable names cannot contain dots.",
                            line_num + 1,
                            var_decl.trim()
                        ));
                    }
                }
            }
        }

        errors
    }

    /// Check if a string is a valid k6 metric name
    ///
    /// k6 metric names must:
    /// - Only contain ASCII letters, numbers, or underscores
    /// - Start with a letter or underscore (not a number)
    /// - Be at most 128 characters
    fn is_valid_k6_metric_name(name: &str) -> bool {
        if name.is_empty() || name.len() > 128 {
            return false;
        }

        let mut chars = name.chars();

        // First character must be a letter or underscore
        if let Some(first) = chars.next() {
            if !first.is_ascii_alphabetic() && first != '_' {
                return false;
            }
        }

        // Remaining characters must be alphanumeric or underscore
        for ch in chars {
            if !ch.is_ascii_alphanumeric() && ch != '_' {
                return false;
            }
        }

        true
    }
}

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

    #[test]
    fn test_k6_config_creation() {
        let config = K6Config {
            target_url: "https://api.example.com".to_string(),
            base_path: None,
            scenario: LoadScenario::RampUp,
            duration_secs: 60,
            max_vus: 10,
            threshold_percentile: "p(95)".to_string(),
            threshold_ms: 500,
            max_error_rate: 0.05,
            auth_header: None,
            custom_headers: HashMap::new(),
            skip_tls_verify: false,
            security_testing_enabled: false,
            chunked_request_bodies: false,
            target_rps: None,
            no_keep_alive: false,
        };

        assert_eq!(config.duration_secs, 60);
        assert_eq!(config.max_vus, 10);
    }

    #[test]
    fn test_script_generator_creation() {
        let config = K6Config {
            target_url: "https://api.example.com".to_string(),
            base_path: None,
            scenario: LoadScenario::Constant,
            duration_secs: 30,
            max_vus: 5,
            threshold_percentile: "p(95)".to_string(),
            threshold_ms: 500,
            max_error_rate: 0.05,
            auth_header: None,
            custom_headers: HashMap::new(),
            skip_tls_verify: false,
            security_testing_enabled: false,
            chunked_request_bodies: false,
            target_rps: None,
            no_keep_alive: false,
        };

        let templates = vec![];
        let generator = K6ScriptGenerator::new(config, templates);

        assert_eq!(generator.templates.len(), 0);
    }

    #[test]
    fn test_sanitize_js_identifier() {
        // Test case from issue #79: names with dots
        assert_eq!(
            K6ScriptGenerator::sanitize_js_identifier("billing.subscriptions.v1"),
            "billing_subscriptions_v1"
        );

        // Test other invalid characters
        assert_eq!(K6ScriptGenerator::sanitize_js_identifier("get user"), "get_user");

        // Test names starting with numbers
        assert_eq!(K6ScriptGenerator::sanitize_js_identifier("123invalid"), "_123invalid");

        // Test already valid identifiers
        assert_eq!(K6ScriptGenerator::sanitize_js_identifier("getUsers"), "getUsers");

        // Test with multiple consecutive invalid chars
        assert_eq!(K6ScriptGenerator::sanitize_js_identifier("test...name"), "test_name");

        // Test empty string (should return default)
        assert_eq!(K6ScriptGenerator::sanitize_js_identifier(""), "operation");

        // Test with special characters
        assert_eq!(K6ScriptGenerator::sanitize_js_identifier("test@name#value"), "test_name_value");

        // Test CRUD flow names with dots (issue #79 follow-up)
        assert_eq!(K6ScriptGenerator::sanitize_js_identifier("plans.list"), "plans_list");
        assert_eq!(K6ScriptGenerator::sanitize_js_identifier("plans.create"), "plans_create");
        assert_eq!(
            K6ScriptGenerator::sanitize_js_identifier("plans.update-pricing-schemes"),
            "plans_update_pricing_schemes"
        );
        assert_eq!(K6ScriptGenerator::sanitize_js_identifier("users CRUD"), "users_CRUD");
    }

    #[test]
    fn test_sanitize_k6_metric_name_short_passthrough() {
        // Names within the limit should pass through unchanged.
        let short = "billing_subscriptions_list";
        let out = K6ScriptGenerator::sanitize_k6_metric_name(short);
        assert_eq!(out, short);
        assert!(K6ScriptGenerator::is_valid_k6_metric_name(&format!("{out}_latency")));
    }

    #[test]
    fn test_sanitize_k6_metric_name_truncates_long_microsoft_graph_id() {
        // Real example from issue #79 (Srikanth's microsoft-graph.yaml run):
        // operationId nested deep enough that the sanitized name + `_latency`
        // exceeds k6's 128-char limit and gets rejected by validate_script.
        let long = "drives.drive.items.driveItem.workbook.worksheets.workbookWorksheet.\
                    charts.workbookChart.axes.categoryAxis.format.line.clear";
        let metric = K6ScriptGenerator::sanitize_k6_metric_name(long);

        // Base must fit within MAX_LEN, leaving room for `_latency` / `_errors`.
        assert!(
            metric.len() <= K6ScriptGenerator::K6_METRIC_NAME_BASE_MAX_LEN,
            "metric base len {} exceeded cap {}",
            metric.len(),
            K6ScriptGenerator::K6_METRIC_NAME_BASE_MAX_LEN
        );

        // Both the bare metric and the suffixed forms must pass k6's validator.
        assert!(K6ScriptGenerator::is_valid_k6_metric_name(&metric));
        assert!(K6ScriptGenerator::is_valid_k6_metric_name(&format!("{metric}_latency")));
        assert!(K6ScriptGenerator::is_valid_k6_metric_name(&format!("{metric}_errors")));
        // Worst-case suffix used by `k6_crud_flow.hbs`.
        assert!(K6ScriptGenerator::is_valid_k6_metric_name(&format!("{metric}_step99_latency")));
    }

    #[test]
    fn test_sanitize_k6_metric_name_distinct_long_names_get_distinct_metrics() {
        // Two long names that share a long common prefix must NOT collide
        // after truncation — the trailing hash makes them distinct.
        let prefix = "a".repeat(150);
        let a = format!("{prefix}.foo");
        let b = format!("{prefix}.bar");
        let ma = K6ScriptGenerator::sanitize_k6_metric_name(&a);
        let mb = K6ScriptGenerator::sanitize_k6_metric_name(&b);
        assert_ne!(ma, mb, "distinct long names produced the same metric name");
    }

    #[test]
    fn test_sanitize_k6_metric_name_truncated_starts_with_letter() {
        // Truncation must preserve the "starts with letter or _" k6 rule.
        let long = format!("{}123end", "x".repeat(120));
        let metric = K6ScriptGenerator::sanitize_k6_metric_name(&long);
        assert!(K6ScriptGenerator::is_valid_k6_metric_name(&metric));
    }

    #[test]
    fn test_microsoft_graph_long_operation_id_passes_validation() {
        // End-to-end: an ApiOperation with a microsoft-graph-style long
        // operationId must produce a script that passes validate_script.
        use crate::spec_parser::ApiOperation;
        use openapiv3::Operation;

        let long_op_id = "drives.drive.items.driveItem.workbook.worksheets.\
            workbookWorksheet.charts.workbookChart.axes.categoryAxis.format.\
            line.clear";

        let operation = ApiOperation {
            method: "post".to_string(),
            path: "/drives/{drive-id}/items/{item-id}/workbook/worksheets/{worksheet-id}/charts/{chart-id}/axes/categoryAxis/format/line/clear".to_string(),
            operation: Operation::default(),
            operation_id: Some(long_op_id.to_string()),
        };
        let template = RequestTemplate {
            operation,
            path_params: HashMap::new(),
            query_params: HashMap::new(),
            headers: HashMap::new(),
            body: None,
        };
        let config = K6Config {
            target_url: "https://api.example.com".to_string(),
            base_path: Some("/v1.0".to_string()),
            scenario: LoadScenario::Constant,
            duration_secs: 30,
            max_vus: 5,
            threshold_percentile: "p(95)".to_string(),
            threshold_ms: 500,
            max_error_rate: 0.05,
            auth_header: None,
            custom_headers: HashMap::new(),
            skip_tls_verify: false,
            security_testing_enabled: false,
            chunked_request_bodies: false,
            target_rps: None,
            no_keep_alive: false,
        };
        let generator = K6ScriptGenerator::new(config, vec![template]);
        let script = generator.generate().expect("script generates");

        let errors = K6ScriptGenerator::validate_script(&script);
        assert!(
            errors.is_empty(),
            "validate_script returned errors for long operationId: {errors:#?}"
        );
    }

    #[test]
    fn test_script_generation_with_dots_in_name() {
        use crate::spec_parser::ApiOperation;
        use openapiv3::Operation;

        // Create an operation with a name containing dots (like in issue #79)
        let operation = ApiOperation {
            method: "get".to_string(),
            path: "/billing/subscriptions".to_string(),
            operation: Operation::default(),
            operation_id: Some("billing.subscriptions.v1".to_string()),
        };

        let template = RequestTemplate {
            operation,
            path_params: HashMap::new(),
            query_params: HashMap::new(),
            headers: HashMap::new(),
            body: None,
        };

        let config = K6Config {
            target_url: "https://api.example.com".to_string(),
            base_path: None,
            scenario: LoadScenario::Constant,
            duration_secs: 30,
            max_vus: 5,
            threshold_percentile: "p(95)".to_string(),
            threshold_ms: 500,
            max_error_rate: 0.05,
            auth_header: None,
            custom_headers: HashMap::new(),
            skip_tls_verify: false,
            security_testing_enabled: false,
            chunked_request_bodies: false,
            target_rps: None,
            no_keep_alive: false,
        };

        let generator = K6ScriptGenerator::new(config, vec![template]);
        let script = generator.generate().expect("Should generate script");

        // Verify the script contains sanitized variable names (no dots in variable identifiers)
        assert!(
            script.contains("const billing_subscriptions_v1_latency"),
            "Script should contain sanitized variable name for latency"
        );
        assert!(
            script.contains("const billing_subscriptions_v1_errors"),
            "Script should contain sanitized variable name for errors"
        );

        // Verify variable names do NOT contain dots (check the actual variable identifier, not string literals)
        // The pattern "const billing.subscriptions" would indicate a variable name with dots
        assert!(
            !script.contains("const billing.subscriptions"),
            "Script should not contain variable names with dots - this would cause 'Unexpected token .' error"
        );

        // Verify metric name strings are sanitized (no dots) - k6 requires valid metric names
        // Metric names must only contain ASCII letters, numbers, or underscores
        assert!(
            script.contains("'billing_subscriptions_v1_latency'"),
            "Metric name strings should be sanitized (no dots) - k6 validation requires valid metric names"
        );
        assert!(
            script.contains("'billing_subscriptions_v1_errors'"),
            "Metric name strings should be sanitized (no dots) - k6 validation requires valid metric names"
        );

        // Verify the original display name is still used in comments and strings (for readability)
        assert!(
            script.contains("billing.subscriptions.v1"),
            "Script should contain original name in comments/strings for readability"
        );

        // Most importantly: verify the variable usage doesn't have dots
        assert!(
            script.contains("billing_subscriptions_v1_latency.add"),
            "Variable usage should use sanitized name"
        );
        assert!(
            script.contains("billing_subscriptions_v1_errors.add"),
            "Variable usage should use sanitized name"
        );
    }

    /// Issue #79 (round 5) regression: `--rps` with the default `ramp-up`
    /// scenario produced 0 requests because the script took
    /// `preAllocatedVUs` from the *last* stage's target — and ramp-up's last
    /// stage is the ramp-DOWN to `target: 0`. The fix is to use the
    /// configured `max_vus` directly when `target_rps` is set, and the full
    /// `duration_secs` rather than the last stage's duration.
    #[test]
    fn test_rps_with_ramp_up_uses_full_vu_pool_and_duration() {
        use crate::spec_parser::ApiOperation;
        use openapiv3::Operation;

        let operation = ApiOperation {
            method: "get".to_string(),
            path: "/users".to_string(),
            operation: Operation::default(),
            operation_id: Some("listUsers".to_string()),
        };
        let template = RequestTemplate {
            operation,
            path_params: HashMap::new(),
            query_params: HashMap::new(),
            headers: HashMap::new(),
            body: None,
        };

        let config = K6Config {
            target_url: "https://api.example.com".to_string(),
            base_path: None,
            scenario: LoadScenario::RampUp,
            duration_secs: 600,
            max_vus: 100,
            threshold_percentile: "p(95)".to_string(),
            threshold_ms: 500,
            max_error_rate: 0.05,
            auth_header: None,
            custom_headers: HashMap::new(),
            skip_tls_verify: false,
            security_testing_enabled: false,
            chunked_request_bodies: false,
            target_rps: Some(100),
            no_keep_alive: false,
        };

        let generator = K6ScriptGenerator::new(config, vec![template]);
        let script = generator.generate().expect("Should generate script");

        assert!(
            script.contains("constant-arrival-rate"),
            "with --rps set, executor must switch to constant-arrival-rate"
        );
        assert!(
            script.contains("rate: 100,"),
            "constant-arrival-rate must use the configured --rps as `rate`"
        );
        assert!(
            script.contains("duration: '600s'"),
            "duration must come from --duration, not the ramp-down stage; got:\n{}",
            script
        );
        assert!(
            script.contains("preAllocatedVUs: 100,"),
            "preAllocatedVUs must equal --vus, not the last stage's target=0; got:\n{}",
            script
        );
        assert!(
            script.contains("maxVUs: 100,"),
            "maxVUs must equal --vus, not the last stage's target=0; got:\n{}",
            script
        );
        // Make sure the regression — `preAllocatedVUs: 0` from the ramp-down —
        // can never silently come back. Walk the lines so we don't false-
        // positive on the explanatory comment that lives in the template.
        for (idx, line) in script.lines().enumerate() {
            let trimmed = line.trim_start();
            if trimmed.starts_with("//") || trimmed.starts_with("/*") {
                continue;
            }
            assert!(
                !trimmed.starts_with("preAllocatedVUs: 0"),
                "regression at line {}: preAllocatedVUs is 0 — constant-arrival-rate \
                 will run no VUs (issue #79 round 5 ramp-up bug). Line: {:?}",
                idx + 1,
                line,
            );
        }
    }

    /// Companion to the test above: confirm `--cps` flips `noConnectionReuse`
    /// on. Issue #79 (round 5).
    #[test]
    fn test_cps_sets_no_connection_reuse() {
        use crate::spec_parser::ApiOperation;
        use openapiv3::Operation;

        let operation = ApiOperation {
            method: "get".to_string(),
            path: "/u".to_string(),
            operation: Operation::default(),
            operation_id: Some("u".to_string()),
        };
        let template = RequestTemplate {
            operation,
            path_params: HashMap::new(),
            query_params: HashMap::new(),
            headers: HashMap::new(),
            body: None,
        };
        let config = K6Config {
            target_url: "https://api.example.com".to_string(),
            base_path: None,
            scenario: LoadScenario::Constant,
            duration_secs: 30,
            max_vus: 5,
            threshold_percentile: "p(95)".to_string(),
            threshold_ms: 500,
            max_error_rate: 0.05,
            auth_header: None,
            custom_headers: HashMap::new(),
            skip_tls_verify: false,
            security_testing_enabled: false,
            chunked_request_bodies: false,
            target_rps: None,
            no_keep_alive: true,
        };
        let script = K6ScriptGenerator::new(config, vec![template]).generate().unwrap();
        assert!(
            script.contains("noConnectionReuse: true"),
            "--cps must set noConnectionReuse: true on the k6 options block"
        );
        assert!(
            script.contains("Total Connections:"),
            "--cps summary must include connection-rate output (Srikanth's round-5 ask)"
        );
        assert!(
            script.contains("Connection Rate:"),
            "--cps summary must include 'Connection Rate:' (Srikanth's round-5 ask)"
        );
    }

    #[test]
    fn test_validate_script_valid() {
        let valid_script = r#"
import http from 'k6/http';
import { check, sleep } from 'k6';
import { Rate, Trend } from 'k6/metrics';

const test_latency = new Trend('test_latency');
const test_errors = new Rate('test_errors');

export default function() {
    const res = http.get('https://example.com');
    test_latency.add(res.timings.duration);
    test_errors.add(res.status !== 200);
}
"#;

        let errors = K6ScriptGenerator::validate_script(valid_script);
        assert!(errors.is_empty(), "Valid script should have no validation errors");
    }

    #[test]
    fn test_validate_script_invalid_metric_name() {
        let invalid_script = r#"
import http from 'k6/http';
import { check, sleep } from 'k6';
import { Rate, Trend } from 'k6/metrics';

const test_latency = new Trend('test.latency');
const test_errors = new Rate('test_errors');

export default function() {
    const res = http.get('https://example.com');
    test_latency.add(res.timings.duration);
}
"#;

        let errors = K6ScriptGenerator::validate_script(invalid_script);
        assert!(
            !errors.is_empty(),
            "Script with invalid metric name should have validation errors"
        );
        assert!(
            errors.iter().any(|e| e.contains("Invalid k6 metric name")),
            "Should detect invalid metric name with dot"
        );
    }

    #[test]
    fn test_validate_script_missing_imports() {
        let invalid_script = r#"
const test_latency = new Trend('test_latency');
export default function() {}
"#;

        let errors = K6ScriptGenerator::validate_script(invalid_script);
        assert!(!errors.is_empty(), "Script missing imports should have validation errors");
    }

    #[test]
    fn test_validate_script_metric_name_validation() {
        // Test that validate_script correctly identifies invalid metric names
        // Valid metric names should pass
        let valid_script = r#"
import http from 'k6/http';
import { check, sleep } from 'k6';
import { Rate, Trend } from 'k6/metrics';
const test_latency = new Trend('test_latency');
const test_errors = new Rate('test_errors');
export default function() {}
"#;
        let errors = K6ScriptGenerator::validate_script(valid_script);
        assert!(errors.is_empty(), "Valid metric names should pass validation");

        // Invalid metric names should fail
        let invalid_cases = vec![
            ("test.latency", "dot in metric name"),
            ("123test", "starts with number"),
            ("test-latency", "hyphen in metric name"),
            ("test@latency", "special character"),
        ];

        for (invalid_name, description) in invalid_cases {
            let script = format!(
                r#"
import http from 'k6/http';
import {{ check, sleep }} from 'k6';
import {{ Rate, Trend }} from 'k6/metrics';
const test_latency = new Trend('{}');
export default function() {{}}
"#,
                invalid_name
            );
            let errors = K6ScriptGenerator::validate_script(&script);
            assert!(
                !errors.is_empty(),
                "Metric name '{}' ({}) should fail validation",
                invalid_name,
                description
            );
        }
    }

    #[test]
    fn test_skip_tls_verify_with_body() {
        use crate::spec_parser::ApiOperation;
        use openapiv3::Operation;
        use serde_json::json;

        // Create an operation with a request body
        let operation = ApiOperation {
            method: "post".to_string(),
            path: "/api/users".to_string(),
            operation: Operation::default(),
            operation_id: Some("createUser".to_string()),
        };

        let template = RequestTemplate {
            operation,
            path_params: HashMap::new(),
            query_params: HashMap::new(),
            headers: HashMap::new(),
            body: Some(json!({"name": "test"})),
        };

        let config = K6Config {
            target_url: "https://api.example.com".to_string(),
            base_path: None,
            scenario: LoadScenario::Constant,
            duration_secs: 30,
            max_vus: 5,
            threshold_percentile: "p(95)".to_string(),
            threshold_ms: 500,
            max_error_rate: 0.05,
            auth_header: None,
            custom_headers: HashMap::new(),
            skip_tls_verify: true,
            security_testing_enabled: false,
            chunked_request_bodies: false,
            target_rps: None,
            no_keep_alive: false,
        };

        let generator = K6ScriptGenerator::new(config, vec![template]);
        let script = generator.generate().expect("Should generate script");

        // Verify the script includes TLS skip option for requests with body
        assert!(
            script.contains("insecureSkipTLSVerify: true"),
            "Script should include insecureSkipTLSVerify option when skip_tls_verify is true"
        );
    }

    #[test]
    fn test_skip_tls_verify_without_body() {
        use crate::spec_parser::ApiOperation;
        use openapiv3::Operation;

        // Create an operation without a request body
        let operation = ApiOperation {
            method: "get".to_string(),
            path: "/api/users".to_string(),
            operation: Operation::default(),
            operation_id: Some("getUsers".to_string()),
        };

        let template = RequestTemplate {
            operation,
            path_params: HashMap::new(),
            query_params: HashMap::new(),
            headers: HashMap::new(),
            body: None,
        };

        let config = K6Config {
            target_url: "https://api.example.com".to_string(),
            base_path: None,
            scenario: LoadScenario::Constant,
            duration_secs: 30,
            max_vus: 5,
            threshold_percentile: "p(95)".to_string(),
            threshold_ms: 500,
            max_error_rate: 0.05,
            auth_header: None,
            custom_headers: HashMap::new(),
            skip_tls_verify: true,
            security_testing_enabled: false,
            chunked_request_bodies: false,
            target_rps: None,
            no_keep_alive: false,
        };

        let generator = K6ScriptGenerator::new(config, vec![template]);
        let script = generator.generate().expect("Should generate script");

        // Verify the script includes TLS skip option for requests without body
        assert!(
            script.contains("insecureSkipTLSVerify: true"),
            "Script should include insecureSkipTLSVerify option when skip_tls_verify is true (no body)"
        );
    }

    #[test]
    fn test_no_skip_tls_verify() {
        use crate::spec_parser::ApiOperation;
        use openapiv3::Operation;

        // Create an operation
        let operation = ApiOperation {
            method: "get".to_string(),
            path: "/api/users".to_string(),
            operation: Operation::default(),
            operation_id: Some("getUsers".to_string()),
        };

        let template = RequestTemplate {
            operation,
            path_params: HashMap::new(),
            query_params: HashMap::new(),
            headers: HashMap::new(),
            body: None,
        };

        let config = K6Config {
            target_url: "https://api.example.com".to_string(),
            base_path: None,
            scenario: LoadScenario::Constant,
            duration_secs: 30,
            max_vus: 5,
            threshold_percentile: "p(95)".to_string(),
            threshold_ms: 500,
            max_error_rate: 0.05,
            auth_header: None,
            custom_headers: HashMap::new(),
            skip_tls_verify: false,
            security_testing_enabled: false,
            chunked_request_bodies: false,
            target_rps: None,
            no_keep_alive: false,
        };

        let generator = K6ScriptGenerator::new(config, vec![template]);
        let script = generator.generate().expect("Should generate script");

        // Verify the script does NOT include TLS skip option when skip_tls_verify is false
        assert!(
            !script.contains("insecureSkipTLSVerify"),
            "Script should NOT include insecureSkipTLSVerify option when skip_tls_verify is false"
        );
    }

    #[test]
    fn test_skip_tls_verify_multiple_operations() {
        use crate::spec_parser::ApiOperation;
        use openapiv3::Operation;
        use serde_json::json;

        // Create multiple operations - one with body, one without
        let operation1 = ApiOperation {
            method: "get".to_string(),
            path: "/api/users".to_string(),
            operation: Operation::default(),
            operation_id: Some("getUsers".to_string()),
        };

        let operation2 = ApiOperation {
            method: "post".to_string(),
            path: "/api/users".to_string(),
            operation: Operation::default(),
            operation_id: Some("createUser".to_string()),
        };

        let template1 = RequestTemplate {
            operation: operation1,
            path_params: HashMap::new(),
            query_params: HashMap::new(),
            headers: HashMap::new(),
            body: None,
        };

        let template2 = RequestTemplate {
            operation: operation2,
            path_params: HashMap::new(),
            query_params: HashMap::new(),
            headers: HashMap::new(),
            body: Some(json!({"name": "test"})),
        };

        let config = K6Config {
            target_url: "https://api.example.com".to_string(),
            base_path: None,
            scenario: LoadScenario::Constant,
            duration_secs: 30,
            max_vus: 5,
            threshold_percentile: "p(95)".to_string(),
            threshold_ms: 500,
            max_error_rate: 0.05,
            auth_header: None,
            custom_headers: HashMap::new(),
            skip_tls_verify: true,
            security_testing_enabled: false,
            chunked_request_bodies: false,
            target_rps: None,
            no_keep_alive: false,
        };

        let generator = K6ScriptGenerator::new(config, vec![template1, template2]);
        let script = generator.generate().expect("Should generate script");

        // Verify the script includes TLS skip option ONCE in global options
        // (k6 only supports insecureSkipTLSVerify as a global option, not per-request)
        let skip_count = script.matches("insecureSkipTLSVerify: true").count();
        assert_eq!(
            skip_count, 1,
            "Script should include insecureSkipTLSVerify exactly once in global options (not per-request)"
        );

        // Verify it appears in the options block, before scenarios
        let options_start = script.find("export const options = {").expect("Should have options");
        let scenarios_start = script.find("scenarios:").expect("Should have scenarios");
        let options_prefix = &script[options_start..scenarios_start];
        assert!(
            options_prefix.contains("insecureSkipTLSVerify: true"),
            "insecureSkipTLSVerify should be in global options block"
        );
    }

    #[test]
    fn test_dynamic_params_in_body() {
        use crate::spec_parser::ApiOperation;
        use openapiv3::Operation;
        use serde_json::json;

        // Create an operation with dynamic placeholders in the body
        let operation = ApiOperation {
            method: "post".to_string(),
            path: "/api/resources".to_string(),
            operation: Operation::default(),
            operation_id: Some("createResource".to_string()),
        };

        let template = RequestTemplate {
            operation,
            path_params: HashMap::new(),
            query_params: HashMap::new(),
            headers: HashMap::new(),
            body: Some(json!({
                "name": "load-test-${__VU}",
                "iteration": "${__ITER}"
            })),
        };

        let config = K6Config {
            target_url: "https://api.example.com".to_string(),
            base_path: None,
            scenario: LoadScenario::Constant,
            duration_secs: 30,
            max_vus: 5,
            threshold_percentile: "p(95)".to_string(),
            threshold_ms: 500,
            max_error_rate: 0.05,
            auth_header: None,
            custom_headers: HashMap::new(),
            skip_tls_verify: false,
            security_testing_enabled: false,
            chunked_request_bodies: false,
            target_rps: None,
            no_keep_alive: false,
        };

        let generator = K6ScriptGenerator::new(config, vec![template]);
        let script = generator.generate().expect("Should generate script");

        // Verify the script contains dynamic body indication
        assert!(
            script.contains("Dynamic body with runtime placeholders"),
            "Script should contain comment about dynamic body"
        );

        // Verify the script contains the __VU variable reference
        assert!(
            script.contains("__VU"),
            "Script should contain __VU reference for dynamic VU-based values"
        );

        // Verify the script contains the __ITER variable reference
        assert!(
            script.contains("__ITER"),
            "Script should contain __ITER reference for dynamic iteration values"
        );
    }

    #[test]
    fn test_dynamic_params_with_uuid() {
        use crate::spec_parser::ApiOperation;
        use openapiv3::Operation;
        use serde_json::json;

        // Create an operation with UUID placeholder
        let operation = ApiOperation {
            method: "post".to_string(),
            path: "/api/resources".to_string(),
            operation: Operation::default(),
            operation_id: Some("createResource".to_string()),
        };

        let template = RequestTemplate {
            operation,
            path_params: HashMap::new(),
            query_params: HashMap::new(),
            headers: HashMap::new(),
            body: Some(json!({
                "id": "${__UUID}"
            })),
        };

        let config = K6Config {
            target_url: "https://api.example.com".to_string(),
            base_path: None,
            scenario: LoadScenario::Constant,
            duration_secs: 30,
            max_vus: 5,
            threshold_percentile: "p(95)".to_string(),
            threshold_ms: 500,
            max_error_rate: 0.05,
            auth_header: None,
            custom_headers: HashMap::new(),
            skip_tls_verify: false,
            security_testing_enabled: false,
            chunked_request_bodies: false,
            target_rps: None,
            no_keep_alive: false,
        };

        let generator = K6ScriptGenerator::new(config, vec![template]);
        let script = generator.generate().expect("Should generate script");

        // As of k6 v1.0.0+, webcrypto is globally available - no import needed
        // Verify the script does NOT include the old experimental webcrypto import
        assert!(
            !script.contains("k6/experimental/webcrypto"),
            "Script should NOT include deprecated k6/experimental/webcrypto import"
        );

        // Verify crypto.randomUUID() is in the generated code
        assert!(
            script.contains("crypto.randomUUID()"),
            "Script should contain crypto.randomUUID() for UUID placeholder"
        );
    }

    #[test]
    fn test_dynamic_params_with_counter() {
        use crate::spec_parser::ApiOperation;
        use openapiv3::Operation;
        use serde_json::json;

        // Create an operation with COUNTER placeholder
        let operation = ApiOperation {
            method: "post".to_string(),
            path: "/api/resources".to_string(),
            operation: Operation::default(),
            operation_id: Some("createResource".to_string()),
        };

        let template = RequestTemplate {
            operation,
            path_params: HashMap::new(),
            query_params: HashMap::new(),
            headers: HashMap::new(),
            body: Some(json!({
                "sequence": "${__COUNTER}"
            })),
        };

        let config = K6Config {
            target_url: "https://api.example.com".to_string(),
            base_path: None,
            scenario: LoadScenario::Constant,
            duration_secs: 30,
            max_vus: 5,
            threshold_percentile: "p(95)".to_string(),
            threshold_ms: 500,
            max_error_rate: 0.05,
            auth_header: None,
            custom_headers: HashMap::new(),
            skip_tls_verify: false,
            security_testing_enabled: false,
            chunked_request_bodies: false,
            target_rps: None,
            no_keep_alive: false,
        };

        let generator = K6ScriptGenerator::new(config, vec![template]);
        let script = generator.generate().expect("Should generate script");

        // Verify the script includes the global counter initialization
        assert!(
            script.contains("let globalCounter = 0"),
            "Script should include globalCounter initialization when COUNTER placeholder is used"
        );

        // Verify globalCounter++ is in the generated code
        assert!(
            script.contains("globalCounter++"),
            "Script should contain globalCounter++ for COUNTER placeholder"
        );
    }

    #[test]
    fn test_static_body_no_dynamic_marker() {
        use crate::spec_parser::ApiOperation;
        use openapiv3::Operation;
        use serde_json::json;

        // Create an operation with static body (no placeholders)
        let operation = ApiOperation {
            method: "post".to_string(),
            path: "/api/resources".to_string(),
            operation: Operation::default(),
            operation_id: Some("createResource".to_string()),
        };

        let template = RequestTemplate {
            operation,
            path_params: HashMap::new(),
            query_params: HashMap::new(),
            headers: HashMap::new(),
            body: Some(json!({
                "name": "static-value",
                "count": 42
            })),
        };

        let config = K6Config {
            target_url: "https://api.example.com".to_string(),
            base_path: None,
            scenario: LoadScenario::Constant,
            duration_secs: 30,
            max_vus: 5,
            threshold_percentile: "p(95)".to_string(),
            threshold_ms: 500,
            max_error_rate: 0.05,
            auth_header: None,
            custom_headers: HashMap::new(),
            skip_tls_verify: false,
            security_testing_enabled: false,
            chunked_request_bodies: false,
            target_rps: None,
            no_keep_alive: false,
        };

        let generator = K6ScriptGenerator::new(config, vec![template]);
        let script = generator.generate().expect("Should generate script");

        // Verify the script does NOT contain dynamic body marker
        assert!(
            !script.contains("Dynamic body with runtime placeholders"),
            "Script should NOT contain dynamic body comment for static body"
        );

        // Verify it does NOT include unnecessary crypto imports
        assert!(
            !script.contains("webcrypto"),
            "Script should NOT include webcrypto import for static body"
        );

        // Verify it does NOT include global counter
        assert!(
            !script.contains("let globalCounter"),
            "Script should NOT include globalCounter for static body"
        );
    }

    #[test]
    fn test_security_testing_enabled_generates_calling_code() {
        use crate::spec_parser::ApiOperation;
        use openapiv3::Operation;
        use serde_json::json;

        let operation = ApiOperation {
            method: "post".to_string(),
            path: "/api/users".to_string(),
            operation: Operation::default(),
            operation_id: Some("createUser".to_string()),
        };

        let template = RequestTemplate {
            operation,
            path_params: HashMap::new(),
            query_params: HashMap::new(),
            headers: HashMap::new(),
            body: Some(json!({"name": "test"})),
        };

        let config = K6Config {
            target_url: "https://api.example.com".to_string(),
            base_path: None,
            scenario: LoadScenario::Constant,
            duration_secs: 30,
            max_vus: 5,
            threshold_percentile: "p(95)".to_string(),
            threshold_ms: 500,
            max_error_rate: 0.05,
            auth_header: None,
            custom_headers: HashMap::new(),
            skip_tls_verify: false,
            security_testing_enabled: true,
            chunked_request_bodies: false,
            target_rps: None,
            no_keep_alive: false,
        };

        let generator = K6ScriptGenerator::new(config, vec![template]);
        let script = generator.generate().expect("Should generate script");

        // Verify calling code is generated (not just function definitions)
        assert!(
            script.contains("getNextSecurityPayload"),
            "Script should contain getNextSecurityPayload() call when security_testing_enabled is true"
        );
        assert!(
            script.contains("applySecurityPayload"),
            "Script should contain applySecurityPayload() call when security_testing_enabled is true"
        );
        assert!(
            script.contains("secPayloadGroup"),
            "Script should contain secPayloadGroup variable when security_testing_enabled is true"
        );
        assert!(
            script.contains("secBodyPayload"),
            "Script should contain secBodyPayload variable when security_testing_enabled is true"
        );
        // Verify CookieJar skip when Cookie header payload is present
        assert!(
            script.contains("hasSecCookie"),
            "Script should track hasSecCookie for CookieJar conflict avoidance"
        );
        assert!(
            script.contains("secRequestOpts"),
            "Script should use secRequestOpts to conditionally skip CookieJar"
        );
        // Verify mutable headers copy for injection
        assert!(
            script.contains("const requestHeaders = { ..."),
            "Script should spread headers into mutable copy for security payload injection"
        );
        // Verify injectAsPath handling for path-based URI injection
        assert!(
            script.contains("secPayload.injectAsPath"),
            "Script should check injectAsPath for path-based URI injection"
        );
        // Verify formBody handling for form-encoded body delivery
        assert!(
            script.contains("secBodyPayload.formBody"),
            "Script should check formBody for form-encoded body delivery"
        );
        assert!(
            script.contains("application/x-www-form-urlencoded"),
            "Script should set Content-Type for form-encoded body"
        );
        // Verify secPayloadGroup is fetched per-operation (inside operation block), not per-iteration
        let op_comment_pos =
            script.find("// Operation 0:").expect("Should have Operation 0 comment");
        let sec_payload_pos = script
            .find("const secPayloadGroup = typeof getNextSecurityPayload")
            .expect("Should have secPayloadGroup assignment");
        assert!(
            sec_payload_pos > op_comment_pos,
            "secPayloadGroup should be fetched inside operation block (per-operation), not before it (per-iteration)"
        );
    }

    #[test]
    fn test_security_testing_disabled_no_calling_code() {
        use crate::spec_parser::ApiOperation;
        use openapiv3::Operation;
        use serde_json::json;

        let operation = ApiOperation {
            method: "post".to_string(),
            path: "/api/users".to_string(),
            operation: Operation::default(),
            operation_id: Some("createUser".to_string()),
        };

        let template = RequestTemplate {
            operation,
            path_params: HashMap::new(),
            query_params: HashMap::new(),
            headers: HashMap::new(),
            body: Some(json!({"name": "test"})),
        };

        let config = K6Config {
            target_url: "https://api.example.com".to_string(),
            base_path: None,
            scenario: LoadScenario::Constant,
            duration_secs: 30,
            max_vus: 5,
            threshold_percentile: "p(95)".to_string(),
            threshold_ms: 500,
            max_error_rate: 0.05,
            auth_header: None,
            custom_headers: HashMap::new(),
            skip_tls_verify: false,
            security_testing_enabled: false,
            chunked_request_bodies: false,
            target_rps: None,
            no_keep_alive: false,
        };

        let generator = K6ScriptGenerator::new(config, vec![template]);
        let script = generator.generate().expect("Should generate script");

        // Verify calling code is NOT generated
        assert!(
            !script.contains("getNextSecurityPayload"),
            "Script should NOT contain getNextSecurityPayload() when security_testing_enabled is false"
        );
        assert!(
            !script.contains("applySecurityPayload"),
            "Script should NOT contain applySecurityPayload() when security_testing_enabled is false"
        );
        assert!(
            !script.contains("secPayloadGroup"),
            "Script should NOT contain secPayloadGroup variable when security_testing_enabled is false"
        );
        assert!(
            !script.contains("secBodyPayload"),
            "Script should NOT contain secBodyPayload variable when security_testing_enabled is false"
        );
        assert!(
            !script.contains("hasSecCookie"),
            "Script should NOT contain hasSecCookie when security_testing_enabled is false"
        );
        assert!(
            !script.contains("secRequestOpts"),
            "Script should NOT contain secRequestOpts when security_testing_enabled is false"
        );
        assert!(
            !script.contains("injectAsPath"),
            "Script should NOT contain injectAsPath when security_testing_enabled is false"
        );
        assert!(
            !script.contains("formBody"),
            "Script should NOT contain formBody when security_testing_enabled is false"
        );
    }

    /// End-to-end test: simulates the real pipeline of template rendering + enhanced script
    /// injection. This is what actually runs when a user passes `--security-test`.
    /// Verifies that the FINAL script has both function definitions AND calling code.
    #[test]
    fn test_security_e2e_definitions_and_calls_both_present() {
        use crate::security_payloads::{
            SecurityPayloads, SecurityTestConfig, SecurityTestGenerator,
        };
        use crate::spec_parser::ApiOperation;
        use openapiv3::Operation;
        use serde_json::json;

        // Step 1: Generate base script with security_testing_enabled=true (template renders calling code)
        let operation = ApiOperation {
            method: "post".to_string(),
            path: "/api/users".to_string(),
            operation: Operation::default(),
            operation_id: Some("createUser".to_string()),
        };

        let template = RequestTemplate {
            operation,
            path_params: HashMap::new(),
            query_params: HashMap::new(),
            headers: HashMap::new(),
            body: Some(json!({"name": "test"})),
        };

        let config = K6Config {
            target_url: "https://api.example.com".to_string(),
            base_path: None,
            scenario: LoadScenario::Constant,
            duration_secs: 30,
            max_vus: 5,
            threshold_percentile: "p(95)".to_string(),
            threshold_ms: 500,
            max_error_rate: 0.05,
            auth_header: None,
            custom_headers: HashMap::new(),
            skip_tls_verify: false,
            security_testing_enabled: true,
            chunked_request_bodies: false,
            target_rps: None,
            no_keep_alive: false,
        };

        let generator = K6ScriptGenerator::new(config, vec![template]);
        let mut script = generator.generate().expect("Should generate base script");

        // Step 2: Simulate what generate_enhanced_script() does — inject function definitions
        let security_config = SecurityTestConfig::default().enable();
        let payloads = SecurityPayloads::get_payloads(&security_config);
        assert!(!payloads.is_empty(), "Should have built-in payloads");

        let mut additional_code = String::new();
        additional_code
            .push_str(&SecurityTestGenerator::generate_payload_selection(&payloads, false));
        additional_code.push('\n');
        additional_code.push_str(&SecurityTestGenerator::generate_apply_payload(&[]));
        additional_code.push('\n');

        // Insert definitions before 'export const options' (same as generate_enhanced_script)
        if let Some(pos) = script.find("export const options") {
            script.insert_str(
                pos,
                &format!("\n// === Advanced Testing Features ===\n{}\n", additional_code),
            );
        }

        // Step 3: Verify the FINAL script has BOTH definitions AND calls
        // Function definitions (injected by generate_enhanced_script)
        assert!(
            script.contains("function getNextSecurityPayload()"),
            "Final script must contain getNextSecurityPayload function DEFINITION"
        );
        assert!(
            script.contains("function applySecurityPayload("),
            "Final script must contain applySecurityPayload function DEFINITION"
        );
        assert!(
            script.contains("securityPayloads"),
            "Final script must contain securityPayloads array"
        );

        // Calling code (rendered by template)
        assert!(
            script.contains("const secPayloadGroup = typeof getNextSecurityPayload"),
            "Final script must contain secPayloadGroup assignment (template calling code)"
        );
        assert!(
            script.contains("applySecurityPayload(payload, [], secBodyPayload)"),
            "Final script must contain applySecurityPayload CALL with secBodyPayload"
        );
        assert!(
            script.contains("const requestHeaders = { ..."),
            "Final script must spread headers for security payload header injection"
        );
        assert!(
            script.contains("for (const secPayload of secPayloadGroup)"),
            "Final script must loop over secPayloadGroup"
        );
        assert!(
            script.contains("secPayload.injectAsPath"),
            "Final script must check injectAsPath for path-based URI injection"
        );
        assert!(
            script.contains("secBodyPayload.formBody"),
            "Final script must check formBody for form-encoded body delivery"
        );

        // Verify ordering: definitions come BEFORE export default function (which has the calls)
        let def_pos = script.find("function getNextSecurityPayload()").unwrap();
        let call_pos =
            script.find("const secPayloadGroup = typeof getNextSecurityPayload").unwrap();
        let options_pos = script.find("export const options").unwrap();
        let default_fn_pos = script.find("export default function").unwrap();

        assert!(
            def_pos < options_pos,
            "Function definitions must appear before export const options"
        );
        assert!(
            call_pos > default_fn_pos,
            "Calling code must appear inside export default function"
        );
    }

    /// Test that URI security payload injection is generated for GET requests
    #[test]
    fn test_security_uri_injection_for_get_requests() {
        use crate::spec_parser::ApiOperation;
        use openapiv3::Operation;

        let operation = ApiOperation {
            method: "get".to_string(),
            path: "/api/users".to_string(),
            operation: Operation::default(),
            operation_id: Some("listUsers".to_string()),
        };

        let template = RequestTemplate {
            operation,
            path_params: HashMap::new(),
            query_params: HashMap::new(),
            headers: HashMap::new(),
            body: None,
        };

        let config = K6Config {
            target_url: "https://api.example.com".to_string(),
            base_path: None,
            scenario: LoadScenario::Constant,
            duration_secs: 30,
            max_vus: 5,
            threshold_percentile: "p(95)".to_string(),
            threshold_ms: 500,
            max_error_rate: 0.05,
            auth_header: None,
            custom_headers: HashMap::new(),
            skip_tls_verify: false,
            security_testing_enabled: true,
            chunked_request_bodies: false,
            target_rps: None,
            no_keep_alive: false,
        };

        let generator = K6ScriptGenerator::new(config, vec![template]);
        let script = generator.generate().expect("Should generate script");

        // Verify URI injection code is present for GET requests
        assert!(
            script.contains("requestUrl"),
            "Script should build requestUrl variable for URI payload injection"
        );
        assert!(
            script.contains("secPayload.location === 'uri'"),
            "Script should check for URI-location payloads"
        );
        // URI payloads are URL-encoded for valid HTTP; WAF decodes before inspection
        assert!(
            script.contains("'test=' + encodeURIComponent(secPayload.payload)"),
            "Script should URL-encode security payload in query string for valid HTTP"
        );
        // Verify injectAsPath check for path-based injection
        assert!(
            script.contains("secPayload.injectAsPath"),
            "Script should check injectAsPath for path-based URI injection"
        );
        assert!(
            script.contains("encodeURI(secPayload.payload)"),
            "Script should use encodeURI for path-based injection"
        );
        // Verify the GET request uses requestUrl
        assert!(
            script.contains("http.get(requestUrl,"),
            "GET request should use requestUrl (with URI injection) instead of inline URL"
        );
    }

    /// Test that URI security payload injection is generated for POST requests with body
    #[test]
    fn test_security_uri_injection_for_post_requests() {
        use crate::spec_parser::ApiOperation;
        use openapiv3::Operation;
        use serde_json::json;

        let operation = ApiOperation {
            method: "post".to_string(),
            path: "/api/users".to_string(),
            operation: Operation::default(),
            operation_id: Some("createUser".to_string()),
        };

        let template = RequestTemplate {
            operation,
            path_params: HashMap::new(),
            query_params: HashMap::new(),
            headers: HashMap::new(),
            body: Some(json!({"name": "test"})),
        };

        let config = K6Config {
            target_url: "https://api.example.com".to_string(),
            base_path: None,
            scenario: LoadScenario::Constant,
            duration_secs: 30,
            max_vus: 5,
            threshold_percentile: "p(95)".to_string(),
            threshold_ms: 500,
            max_error_rate: 0.05,
            auth_header: None,
            custom_headers: HashMap::new(),
            skip_tls_verify: false,
            security_testing_enabled: true,
            chunked_request_bodies: false,
            target_rps: None,
            no_keep_alive: false,
        };

        let generator = K6ScriptGenerator::new(config, vec![template]);
        let script = generator.generate().expect("Should generate script");

        // POST with body should get BOTH URI injection AND body injection
        assert!(
            script.contains("requestUrl"),
            "POST script should build requestUrl for URI payload injection"
        );
        assert!(
            script.contains("secPayload.location === 'uri'"),
            "POST script should check for URI-location payloads"
        );
        assert!(
            script.contains("applySecurityPayload(payload, [], secBodyPayload)"),
            "POST script should apply security body payload to request body"
        );
        // Verify the POST request uses requestUrl
        assert!(
            script.contains("http.post(requestUrl,"),
            "POST request should use requestUrl (with URI injection) instead of inline URL"
        );
    }

    /// Test that security is disabled - no URI injection code present
    #[test]
    fn test_no_uri_injection_when_security_disabled() {
        use crate::spec_parser::ApiOperation;
        use openapiv3::Operation;

        let operation = ApiOperation {
            method: "get".to_string(),
            path: "/api/users".to_string(),
            operation: Operation::default(),
            operation_id: Some("listUsers".to_string()),
        };

        let template = RequestTemplate {
            operation,
            path_params: HashMap::new(),
            query_params: HashMap::new(),
            headers: HashMap::new(),
            body: None,
        };

        let config = K6Config {
            target_url: "https://api.example.com".to_string(),
            base_path: None,
            scenario: LoadScenario::Constant,
            duration_secs: 30,
            max_vus: 5,
            threshold_percentile: "p(95)".to_string(),
            threshold_ms: 500,
            max_error_rate: 0.05,
            auth_header: None,
            custom_headers: HashMap::new(),
            skip_tls_verify: false,
            security_testing_enabled: false,
            chunked_request_bodies: false,
            target_rps: None,
            no_keep_alive: false,
        };

        let generator = K6ScriptGenerator::new(config, vec![template]);
        let script = generator.generate().expect("Should generate script");

        // Verify NO security injection code when disabled
        assert!(
            !script.contains("requestUrl"),
            "Script should NOT have requestUrl when security is disabled"
        );
        assert!(
            !script.contains("secPayloadGroup"),
            "Script should NOT have secPayloadGroup when security is disabled"
        );
        assert!(
            !script.contains("secBodyPayload"),
            "Script should NOT have secBodyPayload when security is disabled"
        );
    }

    /// Test that scripts create a fresh CookieJar per request (not a shared constant)
    #[test]
    fn test_uses_per_request_cookie_jar() {
        use crate::spec_parser::ApiOperation;
        use openapiv3::Operation;

        let operation = ApiOperation {
            method: "get".to_string(),
            path: "/api/users".to_string(),
            operation: Operation::default(),
            operation_id: Some("listUsers".to_string()),
        };

        let template = RequestTemplate {
            operation,
            path_params: HashMap::new(),
            query_params: HashMap::new(),
            headers: HashMap::new(),
            body: None,
        };

        let config = K6Config {
            target_url: "https://api.example.com".to_string(),
            base_path: None,
            scenario: LoadScenario::Constant,
            duration_secs: 30,
            max_vus: 5,
            threshold_percentile: "p(95)".to_string(),
            threshold_ms: 500,
            max_error_rate: 0.05,
            auth_header: None,
            custom_headers: HashMap::new(),
            skip_tls_verify: false,
            security_testing_enabled: false,
            chunked_request_bodies: false,
            target_rps: None,
            no_keep_alive: false,
        };

        let generator = K6ScriptGenerator::new(config, vec![template]);
        let script = generator.generate().expect("Should generate script");

        // Each request must create a fresh CookieJar to prevent Set-Cookie accumulation
        assert!(
            script.contains("jar: new http.CookieJar()"),
            "Script should create fresh CookieJar per request"
        );
        assert!(
            !script.contains("jar: null"),
            "Script should NOT use jar: null (does not disable default VU cookie jar in k6)"
        );
        assert!(
            !script.contains("EMPTY_JAR"),
            "Script should NOT use shared EMPTY_JAR (accumulates Set-Cookie responses)"
        );
    }
}