mockserver-client 7.3.0

An idiomatic Rust client for MockServer's control-plane API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
//! Domain model types for the MockServer control-plane API.
//!
//! All types implement `Serialize`/`Deserialize` and use builder methods that
//! take `self` and return `Self`, enabling fluent construction.

use base64::{engine::general_purpose::STANDARD as BASE64, Engine};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

// ---------------------------------------------------------------------------
// HttpRequest
// ---------------------------------------------------------------------------

/// Matcher for an HTTP request. Uses builder methods for fluent construction.
///
/// # Example
/// ```
/// use mockserver_client::HttpRequest;
///
/// let request = HttpRequest::new()
///     .method("POST")
///     .path("/api/users")
///     .header("Content-Type", "application/json")
///     .query_param("page", "1")
///     .body("{}");
/// ```
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct HttpRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub method: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub query_string_parameters: Option<HashMap<String, Vec<String>>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub headers: Option<HashMap<String, Vec<String>>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub body: Option<Body>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub socket_address: Option<SocketAddress>,
}

impl HttpRequest {
    /// Create a new empty request matcher.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the downstream socket address to connect to.
    ///
    /// Used by load-scenario steps (and forwarded/proxied requests) to direct
    /// the rendered request at a specific host/port/scheme rather than relying
    /// on the request's `Host` header.
    pub fn socket_address(mut self, socket_address: SocketAddress) -> Self {
        self.socket_address = Some(socket_address);
        self
    }

    /// Set the HTTP method to match.
    pub fn method(mut self, method: impl Into<String>) -> Self {
        self.method = Some(method.into());
        self
    }

    /// Set the path to match.
    pub fn path(mut self, path: impl Into<String>) -> Self {
        self.path = Some(path.into());
        self
    }

    /// Add a query string parameter (multiple values per key supported).
    pub fn query_param(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        let params = self
            .query_string_parameters
            .get_or_insert_with(HashMap::new);
        params.entry(key.into()).or_default().push(value.into());
        self
    }

    /// Add a header (multiple values per key supported).
    pub fn header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        let headers = self.headers.get_or_insert_with(HashMap::new);
        headers.entry(key.into()).or_default().push(value.into());
        self
    }

    /// Set a plain string body matcher.
    pub fn body(mut self, body: impl Into<String>) -> Self {
        self.body = Some(Body::Plain(body.into()));
        self
    }

    /// Set a typed JSON body matcher.
    pub fn json_body(mut self, json: serde_json::Value) -> Self {
        self.body = Some(Body::Typed {
            body_type: "JSON".to_string(),
            json: json.to_string(),
        });
        self
    }

    /// Set a file body (type "FILE") with optional content type and template type.
    ///
    /// Use [`Body::file`] for richer construction if you need content type or
    /// template type set.
    pub fn file_body(mut self, file_path: impl Into<String>) -> Self {
        self.body = Some(Body::File {
            file_path: file_path.into(),
            content_type: None,
            template_type: None,
        });
        self
    }

    /// Set a pre-built [`Body`] value (use with [`Body::file`] for FILE bodies).
    pub fn body_value(mut self, body: Body) -> Self {
        self.body = Some(body);
        self
    }
}

// ---------------------------------------------------------------------------
// Body
// ---------------------------------------------------------------------------

/// Request/response body — either a plain string, a typed object, or a file reference.
#[derive(Debug, Clone, PartialEq)]
pub enum Body {
    /// A plain string body.
    Plain(String),
    /// A typed body (e.g., JSON).
    Typed { body_type: String, json: String },
    /// A file body (`type: "FILE"`), with optional template evaluation.
    File {
        file_path: String,
        content_type: Option<String>,
        template_type: Option<String>,
    },
}

impl Body {
    /// Create a FILE body referencing a path on the server filesystem.
    ///
    /// # Example
    /// ```
    /// use mockserver_client::Body;
    ///
    /// let body = Body::file("/data/response.json")
    ///     .with_content_type("application/json")
    ///     .with_template_type("VELOCITY");
    /// ```
    pub fn file(file_path: impl Into<String>) -> Self {
        Body::File {
            file_path: file_path.into(),
            content_type: None,
            template_type: None,
        }
    }

    /// Set the content type on a FILE body. No-op on other variants.
    pub fn with_content_type(mut self, content_type: impl Into<String>) -> Self {
        if let Body::File {
            content_type: ref mut ct,
            ..
        } = self
        {
            *ct = Some(content_type.into());
        }
        self
    }

    /// Set the template type (e.g., "VELOCITY", "MUSTACHE") on a FILE body.
    /// No-op on other variants.
    pub fn with_template_type(mut self, template_type: impl Into<String>) -> Self {
        if let Body::File {
            template_type: ref mut tt,
            ..
        } = self
        {
            *tt = Some(template_type.into());
        }
        self
    }
}

impl Serialize for Body {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        match self {
            Body::Plain(s) => serializer.serialize_str(s),
            Body::Typed { body_type, json } => {
                use serde::ser::SerializeMap;
                let mut map = serializer.serialize_map(Some(2))?;
                map.serialize_entry("type", body_type)?;
                map.serialize_entry("json", json)?;
                map.end()
            }
            Body::File {
                file_path,
                content_type,
                template_type,
            } => {
                use serde::ser::SerializeMap;
                let count = 2
                    + content_type.as_ref().map_or(0, |_| 1)
                    + template_type.as_ref().map_or(0, |_| 1);
                let mut map = serializer.serialize_map(Some(count))?;
                map.serialize_entry("type", "FILE")?;
                map.serialize_entry("filePath", file_path)?;
                if let Some(ct) = content_type {
                    map.serialize_entry("contentType", ct)?;
                }
                if let Some(tt) = template_type {
                    map.serialize_entry("templateType", tt)?;
                }
                map.end()
            }
        }
    }
}

impl<'de> Deserialize<'de> for Body {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        use serde_json::Value;
        let v = Value::deserialize(deserializer)?;
        match v {
            Value::String(s) => Ok(Body::Plain(s)),
            Value::Object(map) => {
                let body_type = map
                    .get("type")
                    .and_then(|v| v.as_str())
                    .unwrap_or("JSON")
                    .to_string();
                if body_type == "FILE" {
                    let file_path = map
                        .get("filePath")
                        .and_then(|v| v.as_str())
                        .unwrap_or("")
                        .to_string();
                    let content_type = map
                        .get("contentType")
                        .and_then(|v| v.as_str())
                        .map(|s| s.to_string());
                    let template_type = map
                        .get("templateType")
                        .and_then(|v| v.as_str())
                        .map(|s| s.to_string());
                    Ok(Body::File {
                        file_path,
                        content_type,
                        template_type,
                    })
                } else {
                    let json = map
                        .get("json")
                        .and_then(|v| v.as_str())
                        .unwrap_or("")
                        .to_string();
                    Ok(Body::Typed { body_type, json })
                }
            }
            _ => Ok(Body::Plain(v.to_string())),
        }
    }
}

// ---------------------------------------------------------------------------
// HttpResponse
// ---------------------------------------------------------------------------

/// Builder for an HTTP response action.
///
/// # Example
/// ```
/// use mockserver_client::HttpResponse;
///
/// let response = HttpResponse::new()
///     .status_code(201)
///     .header("Location", "/api/users/42")
///     .body("{\"id\": 42}");
/// ```
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct HttpResponse {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status_code: Option<u16>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub headers: Option<HashMap<String, Vec<String>>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub body: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub delay: Option<Delay>,
}

impl HttpResponse {
    /// Create a new empty response.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the HTTP status code.
    pub fn status_code(mut self, code: u16) -> Self {
        self.status_code = Some(code);
        self
    }

    /// Add a response header.
    pub fn header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        let headers = self.headers.get_or_insert_with(HashMap::new);
        headers.entry(key.into()).or_default().push(value.into());
        self
    }

    /// Set the response body as a string.
    pub fn body(mut self, body: impl Into<String>) -> Self {
        self.body = Some(body.into());
        self
    }

    /// Set a response delay.
    pub fn delay(mut self, delay: Delay) -> Self {
        self.delay = Some(delay);
        self
    }
}

// ---------------------------------------------------------------------------
// HttpTemplate (response or forward)
// ---------------------------------------------------------------------------

/// Template action — evaluate a response or forward template (Velocity, Mustache, etc.).
///
/// Used as `httpResponseTemplate` or `httpForwardTemplate` in an expectation.
///
/// # Example
/// ```
/// use mockserver_client::HttpTemplate;
///
/// let tmpl = HttpTemplate::new("VELOCITY", "{ \"statusCode\": 200 }")
///     .template_file("/path/to/template.vm");
/// ```
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct HttpTemplate {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub template_type: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub template: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub template_file: Option<String>,
}

impl HttpTemplate {
    /// Create a template action with the given type and inline template body.
    pub fn new(template_type: impl Into<String>, template: impl Into<String>) -> Self {
        Self {
            template_type: Some(template_type.into()),
            template: Some(template.into()),
            template_file: None,
        }
    }

    /// Create a template action that loads from a file path.
    pub fn from_file(template_type: impl Into<String>, file_path: impl Into<String>) -> Self {
        Self {
            template_type: Some(template_type.into()),
            template: None,
            template_file: Some(file_path.into()),
        }
    }

    /// Set the template type (e.g., "VELOCITY", "MUSTACHE").
    pub fn template_type(mut self, template_type: impl Into<String>) -> Self {
        self.template_type = Some(template_type.into());
        self
    }

    /// Set the inline template body.
    pub fn template(mut self, template: impl Into<String>) -> Self {
        self.template = Some(template.into());
        self
    }

    /// Set the template file path (alternative to inline template).
    pub fn template_file(mut self, file_path: impl Into<String>) -> Self {
        self.template_file = Some(file_path.into());
        self
    }
}

// ---------------------------------------------------------------------------
// HttpForward
// ---------------------------------------------------------------------------

/// Forward action — proxy the matched request to another host.
///
/// # Example
/// ```
/// use mockserver_client::HttpForward;
///
/// let forward = HttpForward::new("backend.local", 8080);
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct HttpForward {
    pub host: String,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub port: Option<u16>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub scheme: Option<String>,
}

impl HttpForward {
    /// Create a forward action to the given host and port.
    pub fn new(host: impl Into<String>, port: u16) -> Self {
        Self {
            host: host.into(),
            port: Some(port),
            scheme: None,
        }
    }

    /// Set the scheme (HTTP or HTTPS).
    pub fn scheme(mut self, scheme: impl Into<String>) -> Self {
        self.scheme = Some(scheme.into());
        self
    }
}

// ---------------------------------------------------------------------------
// HttpClassCallback
// ---------------------------------------------------------------------------

/// Class callback action — delegates the response (or forward) to a server-side
/// class that implements MockServer's callback interface.
///
/// This is a purely declarative (REST-only) callback: no WebSocket is involved.
/// The named class must be on the MockServer server's classpath. Serialized as
/// `httpResponseClassCallback` or `httpForwardClassCallback` in an expectation.
///
/// # Example
/// ```
/// use mockserver_client::HttpClassCallback;
///
/// let cb = HttpClassCallback::new("com.example.MyCallback").primary(true);
/// ```
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct HttpClassCallback {
    pub callback_class: String,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub delay: Option<Delay>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub primary: Option<bool>,
}

impl HttpClassCallback {
    /// Create a class callback referencing the fully-qualified class name of a
    /// server-side callback implementation.
    pub fn new(callback_class: impl Into<String>) -> Self {
        Self {
            callback_class: callback_class.into(),
            delay: None,
            primary: None,
        }
    }

    /// Set a delay applied before the callback runs.
    pub fn delay(mut self, delay: Delay) -> Self {
        self.delay = Some(delay);
        self
    }

    /// Mark this callback as primary (kept on the primary event-loop thread).
    pub fn primary(mut self, primary: bool) -> Self {
        self.primary = Some(primary);
        self
    }
}

// ---------------------------------------------------------------------------
// HttpObjectCallback
// ---------------------------------------------------------------------------

/// Object (closure) callback action — delegates the response (or forward) to a
/// client-side closure invoked over the callback WebSocket.
///
/// The `client_id` is the id assigned by MockServer when the client opens the
/// callback WebSocket (`/_mockserver_callback_websocket`). When a request
/// matches, the server pushes it over that socket and the client's registered
/// closure produces the response. Serialized as `httpResponseObjectCallback` or
/// `httpForwardObjectCallback` in an expectation.
///
/// Most users do not construct this directly — use
/// [`MockServerClient::mock_with_callback`](crate::MockServerClient::mock_with_callback),
/// which opens the shared WebSocket, registers the closure, and wires up the
/// `client_id` automatically.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct HttpObjectCallback {
    pub client_id: String,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub response_callback: Option<bool>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub delay: Option<Delay>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub primary: Option<bool>,
}

impl HttpObjectCallback {
    /// Create an object callback bound to the given callback-WebSocket client id.
    pub fn new(client_id: impl Into<String>) -> Self {
        Self {
            client_id: client_id.into(),
            response_callback: None,
            delay: None,
            primary: None,
        }
    }

    /// Set whether the callback also receives the response (forward + response form).
    pub fn response_callback(mut self, response_callback: bool) -> Self {
        self.response_callback = Some(response_callback);
        self
    }

    /// Set a delay applied before the callback runs.
    pub fn delay(mut self, delay: Delay) -> Self {
        self.delay = Some(delay);
        self
    }

    /// Mark this callback as primary (kept on the primary event-loop thread).
    pub fn primary(mut self, primary: bool) -> Self {
        self.primary = Some(primary);
        self
    }
}

// ---------------------------------------------------------------------------
// HttpError
// ---------------------------------------------------------------------------

/// Error action — return a connection-level error to the caller.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct HttpError {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub drop_connection: Option<bool>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub response_bytes: Option<String>,
}

impl HttpError {
    /// Create a new error action.
    pub fn new() -> Self {
        Self::default()
    }

    /// Drop the connection without a response.
    pub fn drop_connection(mut self, drop: bool) -> Self {
        self.drop_connection = Some(drop);
        self
    }

    /// Send arbitrary bytes then close.
    pub fn response_bytes(mut self, bytes: impl Into<String>) -> Self {
        self.response_bytes = Some(bytes.into());
        self
    }
}

// ---------------------------------------------------------------------------
// HttpSseResponse (Server-Sent Events)
// ---------------------------------------------------------------------------

/// A single Server-Sent Event in an [`HttpSseResponse`].
///
/// Maps to the `events[]` entries of the `httpSseResponse` wire shape.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SseEvent {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub event: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub retry: Option<u32>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub delay: Option<Delay>,
}

impl SseEvent {
    /// Create a new empty SSE event.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the `event:` field (event type/name).
    pub fn event(mut self, event: impl Into<String>) -> Self {
        self.event = Some(event.into());
        self
    }

    /// Set the `data:` payload.
    pub fn data(mut self, data: impl Into<String>) -> Self {
        self.data = Some(data.into());
        self
    }

    /// Set the `id:` field.
    pub fn id(mut self, id: impl Into<String>) -> Self {
        self.id = Some(id.into());
        self
    }

    /// Set the `retry:` reconnection time in milliseconds.
    pub fn retry(mut self, retry: u32) -> Self {
        self.retry = Some(retry);
        self
    }

    /// Set a delay before this event is emitted.
    pub fn delay(mut self, delay: Delay) -> Self {
        self.delay = Some(delay);
        self
    }
}

/// Builder for a Server-Sent Events (SSE) streaming response action.
///
/// Serialized as the `httpSseResponse` action in an expectation.
///
/// # Example
/// ```
/// use mockserver_client::{HttpSseResponse, SseEvent};
///
/// let sse = HttpSseResponse::new()
///     .status_code(200)
///     .header("Content-Type", "text/event-stream")
///     .event(SseEvent::new().event("message").data("hello").id("1"))
///     .close_connection(true);
/// ```
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct HttpSseResponse {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status_code: Option<u16>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub headers: Option<HashMap<String, Vec<String>>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub events: Option<Vec<SseEvent>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub close_connection: Option<bool>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub delay: Option<Delay>,
}

impl HttpSseResponse {
    /// Create a new empty SSE response.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the HTTP status code.
    pub fn status_code(mut self, code: u16) -> Self {
        self.status_code = Some(code);
        self
    }

    /// Add a response header.
    pub fn header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        let headers = self.headers.get_or_insert_with(HashMap::new);
        headers.entry(key.into()).or_default().push(value.into());
        self
    }

    /// Append an SSE event to the stream.
    pub fn event(mut self, event: SseEvent) -> Self {
        self.events.get_or_insert_with(Vec::new).push(event);
        self
    }

    /// Replace all SSE events.
    pub fn events(mut self, events: Vec<SseEvent>) -> Self {
        self.events = Some(events);
        self
    }

    /// Whether to close the connection after emitting all events.
    pub fn close_connection(mut self, close: bool) -> Self {
        self.close_connection = Some(close);
        self
    }

    /// Set a delay before the response starts.
    pub fn delay(mut self, delay: Delay) -> Self {
        self.delay = Some(delay);
        self
    }
}

// ---------------------------------------------------------------------------
// HttpWebSocketResponse
// ---------------------------------------------------------------------------

/// A single WebSocket message in an [`HttpWebSocketResponse`].
///
/// Either `text` or `binary` should be set. Binary data is base64-encoded
/// on the wire (the schema declares `binary` as `format: byte`).
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct WebSocketMessage {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub binary: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub delay: Option<Delay>,
}

impl WebSocketMessage {
    /// Create a text WebSocket message.
    pub fn text(text: impl Into<String>) -> Self {
        Self {
            text: Some(text.into()),
            binary: None,
            delay: None,
        }
    }

    /// Create a binary WebSocket message from raw bytes (base64-encoded on the wire).
    pub fn binary(data: impl AsRef<[u8]>) -> Self {
        Self {
            text: None,
            binary: Some(BASE64.encode(data.as_ref())),
            delay: None,
        }
    }

    /// Create a binary WebSocket message from an already base64-encoded string.
    pub fn binary_base64(base64: impl Into<String>) -> Self {
        Self {
            text: None,
            binary: Some(base64.into()),
            delay: None,
        }
    }

    /// Set a delay before this message is sent.
    pub fn delay(mut self, delay: Delay) -> Self {
        self.delay = Some(delay);
        self
    }
}

/// Builder for a WebSocket streaming response action.
///
/// Serialized as the `httpWebSocketResponse` action in an expectation.
///
/// # Example
/// ```
/// use mockserver_client::{HttpWebSocketResponse, WebSocketMessage};
///
/// let ws = HttpWebSocketResponse::new()
///     .subprotocol("chat")
///     .message(WebSocketMessage::text("hello"))
///     .message(WebSocketMessage::binary([0x01, 0x02]))
///     .close_connection(true);
/// ```
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct HttpWebSocketResponse {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub subprotocol: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub messages: Option<Vec<WebSocketMessage>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub close_connection: Option<bool>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub delay: Option<Delay>,
}

impl HttpWebSocketResponse {
    /// Create a new empty WebSocket response.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the negotiated subprotocol.
    pub fn subprotocol(mut self, subprotocol: impl Into<String>) -> Self {
        self.subprotocol = Some(subprotocol.into());
        self
    }

    /// Append a WebSocket message to send.
    pub fn message(mut self, message: WebSocketMessage) -> Self {
        self.messages.get_or_insert_with(Vec::new).push(message);
        self
    }

    /// Replace all WebSocket messages.
    pub fn messages(mut self, messages: Vec<WebSocketMessage>) -> Self {
        self.messages = Some(messages);
        self
    }

    /// Whether to close the connection after emitting all messages.
    pub fn close_connection(mut self, close: bool) -> Self {
        self.close_connection = Some(close);
        self
    }

    /// Set a delay before the response starts.
    pub fn delay(mut self, delay: Delay) -> Self {
        self.delay = Some(delay);
        self
    }
}

// ---------------------------------------------------------------------------
// DnsResponse
// ---------------------------------------------------------------------------

/// A single DNS resource record in a [`DnsResponse`].
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct DnsRecord {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,

    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
    pub record_type: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub dns_class: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub ttl: Option<u32>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub value: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub priority: Option<u32>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub weight: Option<u32>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub port: Option<u16>,
}

impl DnsRecord {
    /// Create a new empty DNS record.
    pub fn new() -> Self {
        Self::default()
    }

    /// Create an `A` (IPv4 address) record.
    pub fn a(name: impl Into<String>, ip: impl Into<String>) -> Self {
        Self::new().name(name).record_type("A").value(ip)
    }

    /// Create an `AAAA` (IPv6 address) record.
    pub fn aaaa(name: impl Into<String>, ip: impl Into<String>) -> Self {
        Self::new().name(name).record_type("AAAA").value(ip)
    }

    /// Create a `CNAME` record.
    pub fn cname(name: impl Into<String>, target: impl Into<String>) -> Self {
        Self::new().name(name).record_type("CNAME").value(target)
    }

    /// Create a `TXT` record.
    pub fn txt(name: impl Into<String>, text: impl Into<String>) -> Self {
        Self::new().name(name).record_type("TXT").value(text)
    }

    /// Set the record name.
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Set the record type (e.g. "A", "AAAA", "CNAME", "MX", "SRV", "TXT", "PTR").
    pub fn record_type(mut self, record_type: impl Into<String>) -> Self {
        self.record_type = Some(record_type.into());
        self
    }

    /// Set the DNS class (e.g. "IN", "CH", "HS", "ANY").
    pub fn dns_class(mut self, dns_class: impl Into<String>) -> Self {
        self.dns_class = Some(dns_class.into());
        self
    }

    /// Set the time-to-live in seconds.
    pub fn ttl(mut self, ttl: u32) -> Self {
        self.ttl = Some(ttl);
        self
    }

    /// Set the record value (address, target, text, etc.).
    pub fn value(mut self, value: impl Into<String>) -> Self {
        self.value = Some(value.into());
        self
    }

    /// Set the priority (MX/SRV).
    pub fn priority(mut self, priority: u32) -> Self {
        self.priority = Some(priority);
        self
    }

    /// Set the weight (SRV).
    pub fn weight(mut self, weight: u32) -> Self {
        self.weight = Some(weight);
        self
    }

    /// Set the port (SRV).
    pub fn port(mut self, port: u16) -> Self {
        self.port = Some(port);
        self
    }
}

/// Builder for a DNS response action.
///
/// Serialized as the `dnsResponse` action in an expectation.
///
/// # Example
/// ```
/// use mockserver_client::{DnsResponse, DnsRecord};
///
/// let dns = DnsResponse::new()
///     .response_code("NOERROR")
///     .answer_record(DnsRecord::a("example.com", "1.2.3.4").ttl(300));
/// ```
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct DnsResponse {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub answer_records: Option<Vec<DnsRecord>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub authority_records: Option<Vec<DnsRecord>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub additional_records: Option<Vec<DnsRecord>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub response_code: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub delay: Option<Delay>,
}

impl DnsResponse {
    /// Create a new empty DNS response.
    pub fn new() -> Self {
        Self::default()
    }

    /// Append an answer-section record.
    pub fn answer_record(mut self, record: DnsRecord) -> Self {
        self.answer_records
            .get_or_insert_with(Vec::new)
            .push(record);
        self
    }

    /// Replace all answer-section records.
    pub fn answer_records(mut self, records: Vec<DnsRecord>) -> Self {
        self.answer_records = Some(records);
        self
    }

    /// Append an authority-section record.
    pub fn authority_record(mut self, record: DnsRecord) -> Self {
        self.authority_records
            .get_or_insert_with(Vec::new)
            .push(record);
        self
    }

    /// Append an additional-section record.
    pub fn additional_record(mut self, record: DnsRecord) -> Self {
        self.additional_records
            .get_or_insert_with(Vec::new)
            .push(record);
        self
    }

    /// Set the DNS response code (e.g. "NOERROR", "NXDOMAIN", "SERVFAIL").
    pub fn response_code(mut self, code: impl Into<String>) -> Self {
        self.response_code = Some(code.into());
        self
    }

    /// Set a delay before the response is returned.
    pub fn delay(mut self, delay: Delay) -> Self {
        self.delay = Some(delay);
        self
    }
}

// ---------------------------------------------------------------------------
// BinaryResponse
// ---------------------------------------------------------------------------

/// Builder for a raw binary response action.
///
/// Serialized as the `binaryResponse` action in an expectation. The binary
/// payload is base64-encoded on the wire (the schema declares `binaryData`
/// as a string).
///
/// # Example
/// ```
/// use mockserver_client::BinaryResponse;
///
/// let resp = BinaryResponse::from_bytes([0xDE, 0xAD, 0xBE, 0xEF]);
/// ```
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct BinaryResponse {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub binary_data: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub delay: Option<Delay>,
}

impl BinaryResponse {
    /// Create a new empty binary response.
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a binary response from raw bytes (base64-encoded on the wire).
    pub fn from_bytes(data: impl AsRef<[u8]>) -> Self {
        Self {
            binary_data: Some(BASE64.encode(data.as_ref())),
            delay: None,
        }
    }

    /// Create a binary response from an already base64-encoded string.
    pub fn from_base64(base64: impl Into<String>) -> Self {
        Self {
            binary_data: Some(base64.into()),
            delay: None,
        }
    }

    /// Set the binary payload from raw bytes (base64-encoded on the wire).
    pub fn binary_data(mut self, data: impl AsRef<[u8]>) -> Self {
        self.binary_data = Some(BASE64.encode(data.as_ref()));
        self
    }

    /// Set a delay before the response is returned.
    pub fn delay(mut self, delay: Delay) -> Self {
        self.delay = Some(delay);
        self
    }
}

// ---------------------------------------------------------------------------
// GrpcStreamResponse
// ---------------------------------------------------------------------------

/// A single gRPC stream message in a [`GrpcStreamResponse`].
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct GrpcStreamMessage {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub json: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub delay: Option<Delay>,
}

impl GrpcStreamMessage {
    /// Create a gRPC stream message from a JSON-encoded protobuf message string.
    pub fn json(json: impl Into<String>) -> Self {
        Self {
            json: Some(json.into()),
            delay: None,
        }
    }

    /// Set a delay before this message is sent.
    pub fn delay(mut self, delay: Delay) -> Self {
        self.delay = Some(delay);
        self
    }
}

/// Builder for a gRPC streaming response action.
///
/// Serialized as the `grpcStreamResponse` action in an expectation.
///
/// # Example
/// ```
/// use mockserver_client::{GrpcStreamResponse, GrpcStreamMessage};
///
/// let grpc = GrpcStreamResponse::new()
///     .status_name("OK")
///     .message(GrpcStreamMessage::json("{\"id\":1}"))
///     .close_connection(true);
/// ```
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct GrpcStreamResponse {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status_name: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub status_message: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub headers: Option<HashMap<String, Vec<String>>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub messages: Option<Vec<GrpcStreamMessage>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub close_connection: Option<bool>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub delay: Option<Delay>,
}

impl GrpcStreamResponse {
    /// Create a new empty gRPC stream response.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the gRPC status name (e.g. "OK", "NOT_FOUND").
    pub fn status_name(mut self, status_name: impl Into<String>) -> Self {
        self.status_name = Some(status_name.into());
        self
    }

    /// Set the gRPC status message.
    pub fn status_message(mut self, status_message: impl Into<String>) -> Self {
        self.status_message = Some(status_message.into());
        self
    }

    /// Add a response header (gRPC metadata).
    pub fn header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        let headers = self.headers.get_or_insert_with(HashMap::new);
        headers.entry(key.into()).or_default().push(value.into());
        self
    }

    /// Append a gRPC stream message.
    pub fn message(mut self, message: GrpcStreamMessage) -> Self {
        self.messages.get_or_insert_with(Vec::new).push(message);
        self
    }

    /// Replace all gRPC stream messages.
    pub fn messages(mut self, messages: Vec<GrpcStreamMessage>) -> Self {
        self.messages = Some(messages);
        self
    }

    /// Whether to close the stream after emitting all messages.
    pub fn close_connection(mut self, close: bool) -> Self {
        self.close_connection = Some(close);
        self
    }

    /// Set a delay before the response starts.
    pub fn delay(mut self, delay: Delay) -> Self {
        self.delay = Some(delay);
        self
    }
}

// ---------------------------------------------------------------------------
// OpenApiExpectation
// ---------------------------------------------------------------------------

/// An OpenAPI specification import — registers matchers and example responses
/// for the operations in an OpenAPI/Swagger spec.
///
/// Sent via `PUT /mockserver/openapi`. The spec may be a URL, a filesystem
/// path (`file://...`), a classpath resource, or an inline JSON/YAML payload.
///
/// # Example
/// ```
/// use mockserver_client::OpenApiExpectation;
///
/// let expectation = OpenApiExpectation::new(
///     "https://example.com/petstore.yaml",
/// )
/// .operation("listPets", "200")
/// .operation("showPetById", "200");
/// ```
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct OpenApiExpectation {
    pub spec_url_or_payload: String,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub operations_and_responses: Option<HashMap<String, String>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub context_path_prefix: Option<String>,
}

impl OpenApiExpectation {
    /// Create an OpenAPI import from a spec URL, file path, classpath resource,
    /// or inline JSON/YAML payload.
    pub fn new(spec_url_or_payload: impl Into<String>) -> Self {
        Self {
            spec_url_or_payload: spec_url_or_payload.into(),
            operations_and_responses: None,
            context_path_prefix: None,
        }
    }

    /// Map an `operationId` to the status code (or example name) to respond with.
    ///
    /// When no operations are specified, MockServer creates example responses
    /// for every operation in the spec.
    pub fn operation(
        mut self,
        operation_id: impl Into<String>,
        status_code: impl Into<String>,
    ) -> Self {
        self.operations_and_responses
            .get_or_insert_with(HashMap::new)
            .insert(operation_id.into(), status_code.into());
        self
    }

    /// Replace the full operations-to-responses map.
    pub fn operations_and_responses(mut self, map: HashMap<String, String>) -> Self {
        self.operations_and_responses = Some(map);
        self
    }

    /// Set a context-path prefix to prepend to every generated matcher path.
    pub fn context_path_prefix(mut self, prefix: impl Into<String>) -> Self {
        self.context_path_prefix = Some(prefix.into());
        self
    }
}

// ---------------------------------------------------------------------------
// Delay
// ---------------------------------------------------------------------------

/// A time delay (e.g., for response delays).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Delay {
    pub time_unit: String,
    pub value: u64,
}

impl Delay {
    /// Create a delay in milliseconds.
    pub fn milliseconds(value: u64) -> Self {
        Self {
            time_unit: "MILLISECONDS".to_string(),
            value,
        }
    }

    /// Create a delay in seconds.
    pub fn seconds(value: u64) -> Self {
        Self {
            time_unit: "SECONDS".to_string(),
            value,
        }
    }
}

// ---------------------------------------------------------------------------
// Times
// ---------------------------------------------------------------------------

/// How many times an expectation should be matched.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Times {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub remaining_times: Option<u32>,

    #[serde(default)]
    pub unlimited: bool,
}

impl Times {
    /// Match unlimited times.
    pub fn unlimited() -> Self {
        Self {
            remaining_times: None,
            unlimited: true,
        }
    }

    /// Match exactly `n` times.
    pub fn exactly(n: u32) -> Self {
        Self {
            remaining_times: Some(n),
            unlimited: false,
        }
    }

    /// Match once.
    pub fn once() -> Self {
        Self::exactly(1)
    }
}

// ---------------------------------------------------------------------------
// TimeToLive
// ---------------------------------------------------------------------------

/// How long an expectation remains active.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct TimeToLive {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub time_unit: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub time_to_live: Option<u64>,

    #[serde(default)]
    pub unlimited: bool,
}

impl TimeToLive {
    /// Unlimited TTL (never expires).
    pub fn unlimited() -> Self {
        Self {
            time_unit: None,
            time_to_live: None,
            unlimited: true,
        }
    }

    /// Expire after the given number of seconds.
    pub fn seconds(seconds: u64) -> Self {
        Self {
            time_unit: Some("SECONDS".to_string()),
            time_to_live: Some(seconds),
            unlimited: false,
        }
    }

    /// Expire after the given number of milliseconds.
    pub fn milliseconds(millis: u64) -> Self {
        Self {
            time_unit: Some("MILLISECONDS".to_string()),
            time_to_live: Some(millis),
            unlimited: false,
        }
    }
}

// ---------------------------------------------------------------------------
// VerificationTimes
// ---------------------------------------------------------------------------

/// Verification constraints — how many times a request must have been received.
///
/// On the wire both `atLeast` and `atMost` are ALWAYS sent, using `-1` to mean
/// "unbounded". The MockServer server deserializes these into primitive `int`
/// fields, so an omitted bound defaults to `0` server-side — which would turn
/// `at_least(n)` into an impossible `between(n, 0)` constraint. Emitting the
/// explicit `-1` sentinel (matching the Java client) avoids that.
#[derive(Debug, Clone, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct VerificationTimes {
    pub at_least: Option<u32>,
    pub at_most: Option<u32>,
}

impl Serialize for VerificationTimes {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        use serde::ser::SerializeStruct;
        let mut state = serializer.serialize_struct("VerificationTimes", 2)?;
        state.serialize_field("atLeast", &self.at_least.map_or(-1_i64, i64::from))?;
        state.serialize_field("atMost", &self.at_most.map_or(-1_i64, i64::from))?;
        state.end()
    }
}

impl VerificationTimes {
    /// Require at least `n` matching requests.
    pub fn at_least(n: u32) -> Self {
        Self {
            at_least: Some(n),
            at_most: None,
        }
    }

    /// Require at most `n` matching requests.
    pub fn at_most(n: u32) -> Self {
        Self {
            at_least: None,
            at_most: Some(n),
        }
    }

    /// Require exactly `n` matching requests.
    pub fn exactly(n: u32) -> Self {
        Self {
            at_least: Some(n),
            at_most: Some(n),
        }
    }

    /// Require between `min` and `max` matching requests (inclusive).
    pub fn between(min: u32, max: u32) -> Self {
        Self {
            at_least: Some(min),
            at_most: Some(max),
        }
    }
}

// ---------------------------------------------------------------------------
// Stateful scenarios
// ---------------------------------------------------------------------------

/// How MockServer selects which of an expectation's multiple `http_responses`
/// to return on each match. Maps to the `responseMode` field.
///
/// - `Sequential` (default) — cycle through the responses in order.
/// - `Random` — pick a response uniformly at random.
/// - `Weighted` — pick a response weighted by the index-aligned
///   [`Expectation::response_weights`].
/// - `Switch` — return the same response for [`Expectation::switch_after`]
///   matches before advancing to the next.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ResponseMode {
    /// Cycle through the responses in order (default).
    Sequential,
    /// Pick a response uniformly at random.
    Random,
    /// Pick a response weighted by [`Expectation::response_weights`].
    Weighted,
    /// Return each response for [`Expectation::switch_after`] matches before advancing.
    Switch,
}

/// The protocol event that triggers a [`CrossProtocolScenario`] state
/// transition. Maps to the `trigger` field.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum CrossProtocolTrigger {
    /// A DNS query is observed.
    DnsQuery,
    /// A WebSocket connection is established.
    WebsocketConnect,
    /// A gRPC request is observed.
    GrpcRequest,
    /// An HTTP request is observed.
    HttpRequest,
}

/// A cross-protocol scenario correlation: when a protocol event matching
/// [`trigger`](Self::trigger) (and optionally [`match_pattern`](Self::match_pattern))
/// is observed, the named scenario is advanced to [`target_state`](Self::target_state).
///
/// Maps to entries of the `crossProtocolScenarios` array.
///
/// # Example
/// ```
/// use mockserver_client::{CrossProtocolScenario, CrossProtocolTrigger};
///
/// let scenario = CrossProtocolScenario::new(
///     CrossProtocolTrigger::DnsQuery,
///     "Deploy",
///     "DnsObserved",
/// )
/// .match_pattern("api.example.com");
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct CrossProtocolScenario {
    pub trigger: CrossProtocolTrigger,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub match_pattern: Option<String>,

    pub scenario_name: String,

    pub target_state: String,
}

impl CrossProtocolScenario {
    /// Create a cross-protocol scenario for the given trigger that advances
    /// `scenario_name` to `target_state` when an event fires.
    pub fn new(
        trigger: CrossProtocolTrigger,
        scenario_name: impl Into<String>,
        target_state: impl Into<String>,
    ) -> Self {
        Self {
            trigger,
            match_pattern: None,
            scenario_name: scenario_name.into(),
            target_state: target_state.into(),
        }
    }

    /// Set the substring filter on the event identifier (omit to match all).
    pub fn match_pattern(mut self, pattern: impl Into<String>) -> Self {
        self.match_pattern = Some(pattern.into());
        self
    }
}

// ---------------------------------------------------------------------------
// Expectation
// ---------------------------------------------------------------------------

/// A full expectation combining a request matcher with an action.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Expectation {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub priority: Option<i32>,

    pub http_request: HttpRequest,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub http_response: Option<HttpResponse>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub http_forward: Option<HttpForward>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub http_response_template: Option<HttpTemplate>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub http_forward_template: Option<HttpTemplate>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub http_error: Option<HttpError>,

    /// Class callback that produces the response (serialized as `httpResponseClassCallback`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub http_response_class_callback: Option<HttpClassCallback>,

    /// Class callback that produces the request to forward (serialized as `httpForwardClassCallback`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub http_forward_class_callback: Option<HttpClassCallback>,

    /// Object/closure callback that produces the response (serialized as `httpResponseObjectCallback`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub http_response_object_callback: Option<HttpObjectCallback>,

    /// Object/closure callback that produces the request to forward (serialized as `httpForwardObjectCallback`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub http_forward_object_callback: Option<HttpObjectCallback>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub http_sse_response: Option<HttpSseResponse>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub http_web_socket_response: Option<HttpWebSocketResponse>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub dns_response: Option<DnsResponse>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub binary_response: Option<BinaryResponse>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub grpc_stream_response: Option<GrpcStreamResponse>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub times: Option<Times>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub time_to_live: Option<TimeToLive>,

    /// Name of the state-machine this expectation participates in.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub scenario_name: Option<String>,

    /// State the scenario must be in for this expectation to match.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub scenario_state: Option<String>,

    /// State the scenario transitions to after this expectation matches.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub new_scenario_state: Option<String>,

    /// Multiple responses; takes priority over the singular [`Expectation::http_response`].
    #[serde(skip_serializing_if = "Option::is_none")]
    pub http_responses: Option<Vec<HttpResponse>>,

    /// How a response is selected from [`Expectation::http_responses`].
    #[serde(skip_serializing_if = "Option::is_none")]
    pub response_mode: Option<ResponseMode>,

    /// Index-aligned relative weights for [`ResponseMode::Weighted`].
    #[serde(skip_serializing_if = "Option::is_none")]
    pub response_weights: Option<Vec<i32>>,

    /// Requests per response block before advancing under [`ResponseMode::Switch`] (default 1).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub switch_after: Option<i32>,

    /// Cross-protocol scenario correlations that advance scenario state on protocol events.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cross_protocol_scenarios: Option<Vec<CrossProtocolScenario>>,
}

impl Expectation {
    /// Create a new expectation with the given request matcher.
    pub fn new(request: HttpRequest) -> Self {
        Self {
            http_request: request,
            ..Default::default()
        }
    }

    /// Set the expectation ID (for upsert semantics).
    pub fn id(mut self, id: impl Into<String>) -> Self {
        self.id = Some(id.into());
        self
    }

    /// Set the priority (higher = matched first).
    pub fn priority(mut self, priority: i32) -> Self {
        self.priority = Some(priority);
        self
    }

    /// Set a response action.
    pub fn respond(mut self, response: HttpResponse) -> Self {
        self.http_response = Some(response);
        self
    }

    /// Set a forward action.
    pub fn forward(mut self, forward: HttpForward) -> Self {
        self.http_forward = Some(forward);
        self
    }

    /// Set a response template action.
    pub fn respond_template(mut self, template: HttpTemplate) -> Self {
        self.http_response_template = Some(template);
        self
    }

    /// Set a forward template action.
    pub fn forward_template(mut self, template: HttpTemplate) -> Self {
        self.http_forward_template = Some(template);
        self
    }

    /// Set an error action.
    pub fn error(mut self, error: HttpError) -> Self {
        self.http_error = Some(error);
        self
    }

    /// Respond via a server-side class callback (`httpResponseClassCallback`).
    ///
    /// The named class must implement MockServer's callback interface and be on
    /// the server's classpath. Convenience over building an [`HttpClassCallback`]
    /// directly; use [`respond_class_callback`](Self::respond_class_callback) for
    /// the full builder (delay, primary).
    pub fn respond_with_class_callback(mut self, callback_class: impl Into<String>) -> Self {
        self.http_response_class_callback = Some(HttpClassCallback::new(callback_class));
        self
    }

    /// Respond via a pre-built [`HttpClassCallback`] (`httpResponseClassCallback`).
    pub fn respond_class_callback(mut self, callback: HttpClassCallback) -> Self {
        self.http_response_class_callback = Some(callback);
        self
    }

    /// Forward via a server-side class callback (`httpForwardClassCallback`).
    pub fn forward_with_class_callback(mut self, callback_class: impl Into<String>) -> Self {
        self.http_forward_class_callback = Some(HttpClassCallback::new(callback_class));
        self
    }

    /// Forward via a pre-built [`HttpClassCallback`] (`httpForwardClassCallback`).
    pub fn forward_class_callback(mut self, callback: HttpClassCallback) -> Self {
        self.http_forward_class_callback = Some(callback);
        self
    }

    /// Respond via an object/closure callback (`httpResponseObjectCallback`).
    ///
    /// Most users should call
    /// [`MockServerClient::mock_with_callback`](crate::MockServerClient::mock_with_callback)
    /// instead, which opens the callback WebSocket, registers the closure, and
    /// fills in the `client_id` automatically.
    pub fn respond_object_callback(mut self, callback: HttpObjectCallback) -> Self {
        self.http_response_object_callback = Some(callback);
        self
    }

    /// Forward via an object/closure callback (`httpForwardObjectCallback`).
    pub fn forward_object_callback(mut self, callback: HttpObjectCallback) -> Self {
        self.http_forward_object_callback = Some(callback);
        self
    }

    /// Set a Server-Sent Events (SSE) response action.
    pub fn respond_sse(mut self, sse: HttpSseResponse) -> Self {
        self.http_sse_response = Some(sse);
        self
    }

    /// Set a WebSocket response action.
    pub fn respond_web_socket(mut self, ws: HttpWebSocketResponse) -> Self {
        self.http_web_socket_response = Some(ws);
        self
    }

    /// Set a DNS response action.
    pub fn respond_dns(mut self, dns: DnsResponse) -> Self {
        self.dns_response = Some(dns);
        self
    }

    /// Set a raw binary response action.
    pub fn respond_binary(mut self, binary: BinaryResponse) -> Self {
        self.binary_response = Some(binary);
        self
    }

    /// Set a gRPC streaming response action.
    pub fn respond_grpc_stream(mut self, grpc: GrpcStreamResponse) -> Self {
        self.grpc_stream_response = Some(grpc);
        self
    }

    /// Set the number of times this expectation matches.
    pub fn times(mut self, times: Times) -> Self {
        self.times = Some(times);
        self
    }

    /// Set the time-to-live.
    pub fn time_to_live(mut self, ttl: TimeToLive) -> Self {
        self.time_to_live = Some(ttl);
        self
    }

    /// Set the scenario (state-machine) name this expectation participates in.
    pub fn scenario_name(mut self, name: impl Into<String>) -> Self {
        self.scenario_name = Some(name.into());
        self
    }

    /// Set the state the scenario must be in for this expectation to match.
    pub fn scenario_state(mut self, state: impl Into<String>) -> Self {
        self.scenario_state = Some(state.into());
        self
    }

    /// Set the state the scenario transitions to after this expectation matches.
    pub fn new_scenario_state(mut self, state: impl Into<String>) -> Self {
        self.new_scenario_state = Some(state.into());
        self
    }

    /// Append a response to the multiple-responses list (`http_responses`).
    ///
    /// When set, `http_responses` takes priority over the singular
    /// [`respond`](Self::respond) action.
    pub fn respond_with(mut self, response: HttpResponse) -> Self {
        self.http_responses
            .get_or_insert_with(Vec::new)
            .push(response);
        self
    }

    /// Replace all multiple responses (`http_responses`).
    pub fn http_responses(mut self, responses: Vec<HttpResponse>) -> Self {
        self.http_responses = Some(responses);
        self
    }

    /// Set how a response is selected from `http_responses`.
    pub fn response_mode(mut self, mode: ResponseMode) -> Self {
        self.response_mode = Some(mode);
        self
    }

    /// Set the index-aligned relative weights for [`ResponseMode::Weighted`].
    pub fn response_weights(mut self, weights: Vec<i32>) -> Self {
        self.response_weights = Some(weights);
        self
    }

    /// Set the number of requests per response block before advancing under
    /// [`ResponseMode::Switch`].
    pub fn switch_after(mut self, switch_after: i32) -> Self {
        self.switch_after = Some(switch_after);
        self
    }

    /// Append a [`CrossProtocolScenario`] correlation.
    pub fn cross_protocol_scenario(mut self, scenario: CrossProtocolScenario) -> Self {
        self.cross_protocol_scenarios
            .get_or_insert_with(Vec::new)
            .push(scenario);
        self
    }

    /// Replace all cross-protocol scenario correlations.
    pub fn cross_protocol_scenarios(mut self, scenarios: Vec<CrossProtocolScenario>) -> Self {
        self.cross_protocol_scenarios = Some(scenarios);
        self
    }
}

// ---------------------------------------------------------------------------
// Verification
// ---------------------------------------------------------------------------

/// A verification request sent to MockServer.
///
/// At least one of `http_request` or `http_response` must be set.
/// `http_response` uses the same [`HttpResponse`] type as expectations —
/// the server matches against the recorded response's status code, headers,
/// and body.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Verification {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub http_request: Option<HttpRequest>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub http_response: Option<HttpResponse>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub times: Option<VerificationTimes>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub maximum_number_of_request_to_return_in_verification_failure: Option<u32>,
}

/// A verification sequence request.
///
/// `http_responses` is index-aligned with `http_requests` — each entry
/// constrains the response that must have been returned for the
/// corresponding request.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct VerificationSequence {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub http_requests: Option<Vec<HttpRequest>>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub http_responses: Option<Vec<HttpResponse>>,
}

// ---------------------------------------------------------------------------
// Ports
// ---------------------------------------------------------------------------

/// Port list (used by status and bind endpoints).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Ports {
    pub ports: Vec<u16>,
}

// ---------------------------------------------------------------------------
// Scenario state
// ---------------------------------------------------------------------------

/// A scenario and its current state, as returned by the scenario REST
/// endpoints (`GET /mockserver/scenario` and `GET /mockserver/scenario/{name}`).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct ScenarioState {
    /// The scenario (state-machine) name.
    pub scenario_name: String,
    /// The scenario's current state.
    pub current_state: String,
}

/// Wrapper for the `GET /mockserver/scenario` list response shape
/// (`{"scenarios":[{"scenarioName","currentState"}]}`).
#[derive(Debug, Clone, Deserialize)]
pub(crate) struct ScenarioList {
    #[serde(default)]
    pub scenarios: Vec<ScenarioState>,
}

// ---------------------------------------------------------------------------
// Retrieve types
// ---------------------------------------------------------------------------

/// The type of data to retrieve from MockServer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RetrieveType {
    /// Recorded inbound requests.
    Requests,
    /// Active (live) expectations.
    ActiveExpectations,
    /// Recorded expectations (from proxy mode).
    RecordedExpectations,
    /// Log messages.
    Logs,
    /// Request/response pairs.
    RequestResponses,
}

impl RetrieveType {
    /// The query parameter value for this type.
    pub fn as_str(&self) -> &'static str {
        match self {
            RetrieveType::Requests => "REQUESTS",
            RetrieveType::ActiveExpectations => "ACTIVE_EXPECTATIONS",
            RetrieveType::RecordedExpectations => "RECORDED_EXPECTATIONS",
            RetrieveType::Logs => "LOGS",
            RetrieveType::RequestResponses => "REQUEST_RESPONSES",
        }
    }
}

/// The response format for retrieve calls.
///
/// In addition to JSON and log-entry formats, MockServer can return the
/// retrieved expectations as SDK setup code (the builder code that recreates
/// the expectations) in a range of languages.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RetrieveFormat {
    Json,
    LogEntries,
    Java,
    JavaScript,
    Python,
    Go,
    CSharp,
    Ruby,
    Rust,
    Php,
}

impl RetrieveFormat {
    /// The query parameter value for this format.
    pub fn as_str(&self) -> &'static str {
        match self {
            RetrieveFormat::Json => "JSON",
            RetrieveFormat::LogEntries => "LOG_ENTRIES",
            RetrieveFormat::Java => "JAVA",
            RetrieveFormat::JavaScript => "JAVASCRIPT",
            RetrieveFormat::Python => "PYTHON",
            RetrieveFormat::Go => "GO",
            RetrieveFormat::CSharp => "CSHARP",
            RetrieveFormat::Ruby => "RUBY",
            RetrieveFormat::Rust => "RUST",
            RetrieveFormat::Php => "PHP",
        }
    }
}

/// The type of data to clear from MockServer.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ClearType {
    All,
    Log,
    Expectations,
}

impl ClearType {
    /// The query parameter value for this type.
    pub fn as_str(&self) -> &'static str {
        match self {
            ClearType::All => "ALL",
            ClearType::Log => "LOG",
            ClearType::Expectations => "EXPECTATIONS",
        }
    }
}

// ---------------------------------------------------------------------------
// Pact verification result
// ---------------------------------------------------------------------------

/// Outcome of a Pact contract verification (`PUT /mockserver/pact/verify`).
///
/// The server replies `202 ACCEPTED` when every interaction in the contract
/// matched an active expectation, or `406 NOT_ACCEPTABLE` when verification
/// failed — in both cases the body is the same verification report JSON.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PactVerification {
    /// `true` when verification passed (`202`), `false` when it failed (`406`).
    pub passed: bool,
    /// The verification report JSON returned by the server (verbatim).
    pub report: String,
}

// ---------------------------------------------------------------------------
// Operating mode
// ---------------------------------------------------------------------------

/// High-level operating mode for MockServer (set via `PUT /mockserver/mode`,
/// read via `GET /mockserver/mode`).
///
/// Each mode packages the common record / replay / pass-through workflows into a
/// single switch (a convenience over `attemptToProxyIfNoMatchingExpectation`):
///
/// * [`MockMode::Simulate`] — match expectations and return mocks; unmatched
///   requests get a `404`. This is the default (proxy-on-no-match disabled).
/// * [`MockMode::Spy`] — match expectations and return mocks, but forward
///   unmatched requests to the real upstream so they are served live and recorded
///   (proxy-on-no-match enabled).
/// * [`MockMode::Capture`] — forward and record; with no expectations defined this
///   captures all traffic. Backed by the same proxy flag as [`MockMode::Spy`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MockMode {
    /// Match expectations; unmatched requests get a `404` (default).
    Simulate,
    /// Match expectations; unmatched requests forwarded to the upstream and recorded.
    Spy,
    /// Forward and record all traffic.
    Capture,
}

impl MockMode {
    /// The wire value for this mode (the `mode` query parameter / JSON field).
    pub fn as_str(&self) -> &'static str {
        match self {
            MockMode::Simulate => "SIMULATE",
            MockMode::Spy => "SPY",
            MockMode::Capture => "CAPTURE",
        }
    }

    /// Whether, in this mode, a request matching no expectation is proxied to its
    /// upstream (and thereby recorded) rather than answered with a `404`.
    pub fn proxy_unmatched_requests(&self) -> bool {
        !matches!(self, MockMode::Simulate)
    }
}

impl std::fmt::Display for MockMode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

impl std::str::FromStr for MockMode {
    type Err = String;

    /// Parse a mode name case-insensitively (matches the server's
    /// `MockMode.parse`). Returns an error message for blank/unknown values.
    fn from_str(value: &str) -> std::result::Result<Self, Self::Err> {
        match value.trim().to_uppercase().as_str() {
            "" => Err("mode is required (one of SIMULATE, SPY, CAPTURE)".to_string()),
            "SIMULATE" => Ok(MockMode::Simulate),
            "SPY" => Ok(MockMode::Spy),
            "CAPTURE" => Ok(MockMode::Capture),
            other => Err(format!(
                "unknown mode '{other}' (expected one of SIMULATE, SPY, CAPTURE)"
            )),
        }
    }
}

// ---------------------------------------------------------------------------
// gRPC descriptor management
// ---------------------------------------------------------------------------

/// A single gRPC method registered from an uploaded descriptor set.
///
/// Returned by [`MockServerClient::retrieve_grpc_services`] as part of a
/// [`GrpcService`]. Maps to the `methods[]` entries of the
/// `PUT /mockserver/grpc/services` wire shape.
///
/// [`MockServerClient::retrieve_grpc_services`]: crate::MockServerClient::retrieve_grpc_services
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct GrpcMethod {
    /// The simple method name (e.g. `SayHello`).
    pub name: String,

    /// Fully-qualified name of the request message type.
    pub input_type: String,

    /// Fully-qualified name of the response message type.
    pub output_type: String,

    /// Whether the method uses client-side streaming.
    pub client_streaming: bool,

    /// Whether the method uses server-side streaming.
    pub server_streaming: bool,
}

/// A gRPC service registered from an uploaded descriptor set.
///
/// Returned by [`MockServerClient::retrieve_grpc_services`]. Maps to the
/// top-level entries of the `PUT /mockserver/grpc/services` wire shape.
///
/// [`MockServerClient::retrieve_grpc_services`]: crate::MockServerClient::retrieve_grpc_services
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct GrpcService {
    /// Fully-qualified service name (e.g. `helloworld.Greeter`).
    pub name: String,

    /// The methods declared by this service.
    pub methods: Vec<GrpcMethod>,
}

// ---------------------------------------------------------------------------
// SocketAddress
// ---------------------------------------------------------------------------

/// A downstream socket address (host / port / scheme) to direct a request at.
///
/// Maps to MockServer's `SocketAddress` model. Used by load-scenario steps to
/// target a specific upstream rather than relying on the `Host` header.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct SocketAddress {
    /// The downstream host name or IP.
    pub host: String,

    /// The downstream port.
    pub port: u16,

    /// The scheme to connect with — `"HTTP"` or `"HTTPS"`. Defaults to `"HTTP"`
    /// on the server when omitted.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub scheme: Option<String>,
}

impl SocketAddress {
    /// Create a plain HTTP socket address.
    pub fn new(host: impl Into<String>, port: u16) -> Self {
        Self {
            host: host.into(),
            port,
            scheme: None,
        }
    }

    /// Set the scheme (`"HTTP"` or `"HTTPS"`).
    pub fn scheme(mut self, scheme: impl Into<String>) -> Self {
        self.scheme = Some(scheme.into());
        self
    }

    /// Convenience: an HTTPS socket address.
    pub fn https(host: impl Into<String>, port: u16) -> Self {
        Self::new(host, port).scheme("HTTPS")
    }
}

// ---------------------------------------------------------------------------
// Load scenario registry (PUT/GET/DELETE /mockserver/loadScenario[/...])
// ---------------------------------------------------------------------------

/// The interpolation curve used to ramp a value (virtual users or arrival
/// rate) from a start setpoint to an end setpoint across a ramp [`LoadStage`].
/// Maps to the `RampCurve` schema. Only meaningful for ramp stages; ignored for
/// holds and pauses.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum RampCurve {
    /// Constant slope.
    Linear,
    /// Ease-in: slow then fast.
    Quadratic,
    /// A steeper ease-in.
    Exponential,
}

/// The kind of a [`LoadStage`].
///
/// - `Vu` — closed model: hold or ramp the number of concurrent virtual users.
/// - `Rate` — open model: hold or ramp an arrival rate in iterations/second.
/// - `Pause` — drive no load for the duration.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum LoadStageType {
    /// Closed model — hold or ramp concurrent virtual users.
    Vu,
    /// Open model — hold or ramp an arrival rate in iterations/second.
    Rate,
    /// Drive no load for the duration.
    Pause,
}

/// One stage of a [`LoadProfile`]: a contiguous slice of the run holding or
/// ramping a setpoint for `duration_millis`. Stages run in sequence. Maps to the
/// `LoadStage` schema.
///
/// Use the constructors [`LoadStage::vu_hold`], [`LoadStage::vu_ramp`],
/// [`LoadStage::rate_hold`], [`LoadStage::rate_ramp`] and [`LoadStage::pause`]
/// rather than building the struct directly so only the relevant fields are set
/// (and therefore serialized).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct LoadStage {
    /// The kind of stage — `VU`, `RATE` or `PAUSE`.
    #[serde(rename = "type")]
    pub stage_type: LoadStageType,

    /// How long this stage runs in milliseconds (> 0).
    pub duration_millis: u64,

    /// Ramp shape (ramp stages only); omitted for holds and pauses.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub curve: Option<RampCurve>,

    /// VU hold: the number of virtual users to hold for the stage.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub vus: Option<u32>,

    /// VU ramp: virtual users at the start of the ramp.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_vus: Option<u32>,

    /// VU ramp: virtual users at the end of the ramp.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end_vus: Option<u32>,

    /// RATE hold: arrival rate to hold, in iterations per second.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rate: Option<f64>,

    /// RATE ramp: arrival rate at the start of the ramp, in iterations/second.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_rate: Option<f64>,

    /// RATE ramp: arrival rate at the end of the ramp, in iterations/second.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub end_rate: Option<f64>,

    /// RATE stage only: optional cap on the auto-scaling virtual-user pool.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_vus: Option<u32>,
}

impl LoadStage {
    fn base(stage_type: LoadStageType, duration_millis: u64) -> Self {
        Self {
            stage_type,
            duration_millis,
            curve: None,
            vus: None,
            start_vus: None,
            end_vus: None,
            rate: None,
            start_rate: None,
            end_rate: None,
            max_vus: None,
        }
    }

    /// A VU stage holding `vus` virtual users for `duration_millis`.
    pub fn vu_hold(vus: u32, duration_millis: u64) -> Self {
        let mut stage = Self::base(LoadStageType::Vu, duration_millis);
        stage.vus = Some(vus);
        stage
    }

    /// A VU stage ramping from `start_vus` to `end_vus` over `duration_millis`
    /// along `curve`.
    pub fn vu_ramp(start_vus: u32, end_vus: u32, duration_millis: u64, curve: RampCurve) -> Self {
        let mut stage = Self::base(LoadStageType::Vu, duration_millis);
        stage.start_vus = Some(start_vus);
        stage.end_vus = Some(end_vus);
        stage.curve = Some(curve);
        stage
    }

    /// A RATE stage holding `rate` iterations/second for `duration_millis`.
    pub fn rate_hold(rate: f64, duration_millis: u64) -> Self {
        let mut stage = Self::base(LoadStageType::Rate, duration_millis);
        stage.rate = Some(rate);
        stage
    }

    /// A RATE stage ramping from `start_rate` to `end_rate` iterations/second
    /// over `duration_millis` along `curve`.
    pub fn rate_ramp(
        start_rate: f64,
        end_rate: f64,
        duration_millis: u64,
        curve: RampCurve,
    ) -> Self {
        let mut stage = Self::base(LoadStageType::Rate, duration_millis);
        stage.start_rate = Some(start_rate);
        stage.end_rate = Some(end_rate);
        stage.curve = Some(curve);
        stage
    }

    /// A PAUSE stage that drives no load for `duration_millis`.
    pub fn pause(duration_millis: u64) -> Self {
        Self::base(LoadStageType::Pause, duration_millis)
    }

    /// Cap the auto-scaling virtual-user pool for this RATE stage.
    pub fn max_vus(mut self, max_vus: u32) -> Self {
        self.max_vus = Some(max_vus);
        self
    }
}

/// A named load shape that expands server-side into ordinary [`LoadStage`]s.
/// Maps to the `LoadShapeType` schema.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum LoadShapeType {
    /// Ramp up, hold the peak, ramp back down, with an optional recovery hold.
    Spike,
    /// A flight of pure-hold steps, each one "step" higher.
    Stairs,
    /// Ramp 0 to target then hold.
    RampHold,
}

/// What a [`LoadShape`] drives. Maps to the `LoadShapeMetric` schema.
///
/// - `Vu` — concurrent virtual users (closed model).
/// - `Rate` — arrival rate in iterations/second (open model).
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum LoadShapeMetric {
    /// Concurrent virtual users (closed model).
    Vu,
    /// Arrival rate in iterations/second (open model).
    Rate,
}

/// A declarative named load shape that expands into ordinary [`LoadStage`]s.
/// Maps to the `LoadShape` schema. Only the parameters its `type` needs are
/// read; the rest are ignored. Use a shape OR an explicit `stages` list, not
/// both.
///
/// Use the constructors [`LoadShape::spike`], [`LoadShape::stairs`] and
/// [`LoadShape::ramp_hold`] so only the relevant fields are set (and therefore
/// serialized).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct LoadShape {
    /// The named shape — `SPIKE`, `STAIRS` or `RAMP_HOLD`.
    #[serde(rename = "type")]
    pub shape_type: LoadShapeType,

    /// What the shape drives — `VU` (default) or `RATE`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metric: Option<LoadShapeMetric>,

    /// Ramp interpolation curve used by the shape's ramps.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub curve: Option<RampCurve>,

    /// SPIKE: the level held before and after the spike.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub baseline: Option<f64>,

    /// SPIKE: the level held at the top of the spike.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub peak: Option<f64>,

    /// SPIKE: duration of the baseline to peak ramp.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ramp_up_millis: Option<u64>,

    /// SPIKE: duration to hold at the peak; RAMP_HOLD: duration to hold at the
    /// target.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub hold_millis: Option<u64>,

    /// SPIKE: duration of the peak to baseline ramp.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ramp_down_millis: Option<u64>,

    /// SPIKE (optional): duration to hold at baseline after the down ramp.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recovery_hold_millis: Option<u64>,

    /// STAIRS: the level of the first step.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start: Option<f64>,

    /// STAIRS: how much each step rises above the previous one.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub step: Option<f64>,

    /// STAIRS: the number of steps.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub steps: Option<u32>,

    /// STAIRS: how long each step holds at its level.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub step_duration_millis: Option<u64>,

    /// RAMP_HOLD: the level ramped up to (from 0) and then held.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub target: Option<f64>,

    /// RAMP_HOLD: duration of the 0 to target ramp.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ramp_millis: Option<u64>,
}

impl LoadShape {
    fn base(shape_type: LoadShapeType) -> Self {
        Self {
            shape_type,
            metric: None,
            curve: None,
            baseline: None,
            peak: None,
            ramp_up_millis: None,
            hold_millis: None,
            ramp_down_millis: None,
            recovery_hold_millis: None,
            start: None,
            step: None,
            steps: None,
            step_duration_millis: None,
            target: None,
            ramp_millis: None,
        }
    }

    /// A SPIKE shape: ramp `baseline` to `peak` over `ramp_up_millis`, hold for
    /// `hold_millis`, then ramp back down over `ramp_down_millis`.
    pub fn spike(
        baseline: f64,
        peak: f64,
        ramp_up_millis: u64,
        hold_millis: u64,
        ramp_down_millis: u64,
    ) -> Self {
        let mut shape = Self::base(LoadShapeType::Spike);
        shape.baseline = Some(baseline);
        shape.peak = Some(peak);
        shape.ramp_up_millis = Some(ramp_up_millis);
        shape.hold_millis = Some(hold_millis);
        shape.ramp_down_millis = Some(ramp_down_millis);
        shape
    }

    /// A STAIRS shape: `steps` pure-hold steps, the first at `start` and each
    /// rising by `step`, every step holding for `step_duration_millis`.
    pub fn stairs(start: f64, step: f64, steps: u32, step_duration_millis: u64) -> Self {
        let mut shape = Self::base(LoadShapeType::Stairs);
        shape.start = Some(start);
        shape.step = Some(step);
        shape.steps = Some(steps);
        shape.step_duration_millis = Some(step_duration_millis);
        shape
    }

    /// A RAMP_HOLD shape: ramp from 0 to `target` over `ramp_millis`, then hold
    /// for `hold_millis`.
    pub fn ramp_hold(target: f64, ramp_millis: u64, hold_millis: u64) -> Self {
        let mut shape = Self::base(LoadShapeType::RampHold);
        shape.target = Some(target);
        shape.ramp_millis = Some(ramp_millis);
        shape.hold_millis = Some(hold_millis);
        shape
    }

    /// Set what the shape drives (`VU` or `RATE`).
    pub fn metric(mut self, metric: LoadShapeMetric) -> Self {
        self.metric = Some(metric);
        self
    }

    /// Set the ramp interpolation curve.
    pub fn curve(mut self, curve: RampCurve) -> Self {
        self.curve = Some(curve);
        self
    }

    /// SPIKE only: hold at baseline for `recovery_hold_millis` after the down
    /// ramp.
    pub fn recovery_hold_millis(mut self, recovery_hold_millis: u64) -> Self {
        self.recovery_hold_millis = Some(recovery_hold_millis);
        self
    }
}

/// The per-run metric a [`LoadThreshold`] evaluates. Maps to the threshold
/// `metric` enum.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum LoadThresholdMetric {
    /// 50th-percentile latency in milliseconds.
    LatencyP50,
    /// 95th-percentile latency in milliseconds.
    LatencyP95,
    /// 99th-percentile latency in milliseconds.
    LatencyP99,
    /// 99.9th-percentile latency in milliseconds.
    LatencyP999,
    /// Failed / requests, as a 0.0-1.0 fraction.
    ErrorRate,
    /// Throughput in requests/second over the run's elapsed time.
    ThroughputRps,
}

/// How a [`LoadThreshold`]'s observed value is compared to its threshold. Maps
/// to the threshold `comparator` enum.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum LoadComparator {
    /// observed < threshold.
    LessThan,
    /// observed <= threshold.
    LessThanOrEqual,
    /// observed > threshold.
    GreaterThan,
    /// observed >= threshold.
    GreaterThanOrEqual,
}

/// An in-run pass/fail threshold for a load scenario: a per-run metric compared
/// against a value. All thresholds must hold for the run verdict to be PASS
/// (logical AND). Maps to the `LoadThreshold` schema.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct LoadThreshold {
    /// The per-run metric to evaluate.
    pub metric: LoadThresholdMetric,

    /// How the observed per-run value is compared to the threshold.
    pub comparator: LoadComparator,

    /// The threshold value (milliseconds for latency metrics, a 0.0-1.0
    /// fraction for `ERROR_RATE`, requests/second for `THROUGHPUT_RPS`).
    pub threshold: f64,
}

impl LoadThreshold {
    /// Create a threshold comparing `metric` to `threshold` using `comparator`.
    pub fn new(metric: LoadThresholdMetric, comparator: LoadComparator, threshold: f64) -> Self {
        Self {
            metric,
            comparator,
            threshold,
        }
    }
}

/// How a [`LoadPacing`] target iteration cycle is derived from its value. Maps
/// to the pacing `mode` enum.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum LoadPacingMode {
    /// No pacing (immediate reschedule).
    None,
    /// `value` is the target cycle in milliseconds.
    ConstantPacing,
    /// `value` is the target iterations/second per VU (cycle = 1000 / value ms).
    ConstantThroughput,
}

/// Adaptive iteration pacing (think-time) for a load scenario: a target
/// per-virtual-user iteration cycle time. Applies only to the closed-model VU
/// loop. Maps to the `LoadPacing` schema.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct LoadPacing {
    /// How the target iteration cycle is derived from `value`.
    pub mode: LoadPacingMode,

    /// For `CONSTANT_PACING` the target cycle in milliseconds; for
    /// `CONSTANT_THROUGHPUT` the target iterations/second per VU. Must be > 0
    /// when `mode` is not `NONE`.
    pub value: f64,
}

impl LoadPacing {
    /// Create a pacing rule with the given mode and value.
    pub fn new(mode: LoadPacingMode, value: f64) -> Self {
        Self { mode, value }
    }

    /// `CONSTANT_PACING`: target a per-VU iteration cycle of `cycle_millis`.
    pub fn constant_pacing(cycle_millis: f64) -> Self {
        Self::new(LoadPacingMode::ConstantPacing, cycle_millis)
    }

    /// `CONSTANT_THROUGHPUT`: target `iterations_per_second` per VU.
    pub fn constant_throughput(iterations_per_second: f64) -> Self {
        Self::new(LoadPacingMode::ConstantThroughput, iterations_per_second)
    }
}

/// The format of a [`LoadFeeder`]'s raw `data`. Maps to the feeder `format`
/// enum.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum LoadFeederFormat {
    /// CSV: first line is the header row.
    Csv,
    /// JSON: an array of flat objects.
    Json,
}

/// How a [`LoadFeeder`] selects a row each iteration. Maps to the feeder
/// `strategy` enum.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum LoadFeederStrategy {
    /// Cycle rows and never exhaust (default).
    Circular,
    /// Pick a uniformly random row each iteration.
    Random,
    /// Use each row once in order; COMPLETES the run when exhausted.
    Sequential,
}

/// Parameterized test data (a data feeder) for a load scenario: an inline
/// dataset from which one row is selected per iteration and exposed to the
/// iteration's templates as `$iteration.data.<column>`. Supply EITHER `rows`
/// (the primary form) OR `data` + `format`. Maps to the `LoadFeeder` schema.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct LoadFeeder {
    /// Inline dataset: a list of column-name to value maps, one per row.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub rows: Vec<HashMap<String, String>>,

    /// Optional raw inline dataset parsed server-side into rows per `format`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<String>,

    /// The format of `data` (required when `data` is set).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub format: Option<LoadFeederFormat>,

    /// How a row is chosen each iteration.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub strategy: Option<LoadFeederStrategy>,
}

impl LoadFeeder {
    /// A feeder from an inline list of column-name to value rows.
    pub fn rows(rows: Vec<HashMap<String, String>>) -> Self {
        Self {
            rows,
            ..Self::default()
        }
    }

    /// A feeder from raw inline `data` parsed server-side as `format`.
    pub fn data(data: impl Into<String>, format: LoadFeederFormat) -> Self {
        Self {
            data: Some(data.into()),
            format: Some(format),
            ..Self::default()
        }
    }

    /// Set the row-selection strategy.
    pub fn strategy(mut self, strategy: LoadFeederStrategy) -> Self {
        self.strategy = Some(strategy);
        self
    }
}

/// Where a [`LoadCapture`] extracts its value from. Maps to the capture
/// `source` enum.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum LoadCaptureSource {
    /// A JSONPath over the response body.
    BodyJsonpath,
    /// A response header value.
    Header,
    /// A regex over the response body string (capture group 1).
    BodyRegex,
}

/// A declarative cross-step capture / correlation rule: extracts a value from a
/// step's response and binds it to a variable name a later step in the same
/// iteration can reference via `$iteration.captured.<name>`. Best-effort. Maps
/// to the `LoadCapture` schema.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct LoadCapture {
    /// The variable name later steps reference.
    pub name: String,

    /// Where to extract from.
    pub source: LoadCaptureSource,

    /// The JSONPath, header name, or regex driving the extraction.
    pub expression: String,

    /// Optional fallback value bound when extraction yields nothing.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub default_value: Option<String>,
}

impl LoadCapture {
    /// Create a capture binding `name` to the value extracted from `source` via
    /// `expression`.
    pub fn new(
        name: impl Into<String>,
        source: LoadCaptureSource,
        expression: impl Into<String>,
    ) -> Self {
        Self {
            name: name.into(),
            source,
            expression: expression.into(),
            default_value: None,
        }
    }

    /// Set the fallback value bound to the variable on no match.
    pub fn default_value(mut self, default_value: impl Into<String>) -> Self {
        self.default_value = Some(default_value.into());
        self
    }
}

/// How each iteration of a load scenario selects which steps to run. Maps to
/// the `stepSelection` enum.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum LoadStepSelection {
    /// Run ALL steps in declared order (a multi-step user journey).
    Sequential,
    /// Run exactly ONE step per iteration chosen at random by weight.
    Weighted,
}

/// The load profile of a load scenario: EITHER an ordered list of [`LoadStage`]s
/// run in sequence, OR a single named [`LoadShape`] that expands into stages.
/// Maps to the `LoadProfile` schema.
///
/// Use [`LoadProfile::of`] to build from a list of stages, the convenience
/// constructors [`LoadProfile::constant`] / [`LoadProfile::linear`] for a single
/// VU stage, or [`LoadProfile::shaped`] for a named shape.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct LoadProfile {
    /// Ordered stages run one after another. Omitted (empty) when a `shape` is
    /// used.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub stages: Vec<LoadStage>,

    /// A named shape that expands server-side into stages. Use a shape OR
    /// `stages`, not both.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub shape: Option<LoadShape>,
}

impl LoadProfile {
    /// A profile from an explicit list of stages.
    pub fn of(stages: Vec<LoadStage>) -> Self {
        Self {
            stages,
            shape: None,
        }
    }

    /// A profile from a single named [`LoadShape`].
    pub fn shaped(shape: LoadShape) -> Self {
        Self {
            stages: Vec::new(),
            shape: Some(shape),
        }
    }

    /// A single VU stage holding `vus` virtual users for `duration_millis`.
    pub fn constant(vus: u32, duration_millis: u64) -> Self {
        Self::of(vec![LoadStage::vu_hold(vus, duration_millis)])
    }

    /// A single linear VU ramp from `start_vus` to `end_vus` over
    /// `duration_millis`.
    pub fn linear(start_vus: u32, end_vus: u32, duration_millis: u64) -> Self {
        Self::of(vec![LoadStage::vu_ramp(
            start_vus,
            end_vus,
            duration_millis,
            RampCurve::Linear,
        )])
    }

    /// Append a stage and return the profile.
    pub fn add_stage(mut self, stage: LoadStage) -> Self {
        self.stages.push(stage);
        self
    }
}

/// A single templated request step in a load scenario. Maps to the `LoadStep`
/// schema.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct LoadStep {
    /// The templated request to fire each iteration.
    pub request: HttpRequest,

    /// Optional inter-step pause (a [`Delay`]).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub think_time: Option<Delay>,

    /// Optional cross-step capture rules applied to this step's response. Each
    /// binds an extracted value to a variable name visible to SUBSEQUENT steps
    /// in the same iteration.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub captures: Vec<LoadCapture>,

    /// Relative selection weight, used only when the scenario's
    /// `stepSelection` is `WEIGHTED`. Must be > 0 when `WEIGHTED`; ignored
    /// under the default `SEQUENTIAL` mode.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub weight: Option<f64>,
}

impl LoadStep {
    /// Create a step from a request matcher/template.
    pub fn new(request: HttpRequest) -> Self {
        Self {
            request,
            think_time: None,
            captures: Vec::new(),
            weight: None,
        }
    }

    /// Set the inter-step pause.
    pub fn think_time(mut self, delay: Delay) -> Self {
        self.think_time = Some(delay);
        self
    }

    /// Append a cross-step capture rule applied to this step's response.
    pub fn capture(mut self, capture: LoadCapture) -> Self {
        self.captures.push(capture);
        self
    }

    /// Set the relative selection weight (used only under `WEIGHTED`
    /// `stepSelection`).
    pub fn weight(mut self, weight: f64) -> Self {
        self.weight = Some(weight);
        self
    }
}

/// An API-driven load scenario: ordered templated steps driven at a target
/// concurrency. Maps to the `LoadScenario` schema (the body of
/// `PUT /mockserver/loadScenario`, which registers the scenario in the
/// registry without running it). The unique [`name`](LoadScenario::name) is the
/// registry key used by `start`/`stop` and the per-scenario `GET`/`DELETE`
/// endpoints.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct LoadScenario {
    /// Human-readable scenario name.
    pub name: String,

    /// Template engine for per-iteration rendering — `"VELOCITY"` (default) or
    /// `"MUSTACHE"`. (JavaScript is rejected for load steps.)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub template_type: Option<String>,

    /// Optional hard cap on the total number of requests dispatched.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_requests: Option<u64>,

    /// Optional delay (milliseconds) applied between a `start` request being
    /// accepted and the scenario actually beginning to drive load. Honoured by
    /// `PUT /mockserver/loadScenario/start`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub start_delay_millis: Option<u64>,

    /// Optional in-run pass/fail thresholds; the run carries a PASS verdict iff
    /// all hold, FAIL otherwise. Empty/omitted means no verdict is computed.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub thresholds: Vec<LoadThreshold>,

    /// When true, a FAIL verdict aborts the run early. Default false (omitted).
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    pub abort_on_fail: bool,

    /// Suppress `abort_on_fail` for the first N milliseconds of the run so noisy
    /// startup samples cannot trigger a premature abort.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub abort_grace_millis: Option<u64>,

    /// Optional adaptive iteration pacing (closed-model VU loop only).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pacing: Option<LoadPacing>,

    /// Optional parameterized test data (a data feeder).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub feeder: Option<LoadFeeder>,

    /// How each iteration selects which steps to run — `SEQUENTIAL` (default,
    /// omitted) or `WEIGHTED`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub step_selection: Option<LoadStepSelection>,

    /// The ramp profile.
    pub profile: LoadProfile,

    /// Ordered list of request steps fired in sequence each iteration (max 50).
    pub steps: Vec<LoadStep>,
}

impl LoadScenario {
    /// Create a scenario with the given name, profile and steps.
    pub fn new(name: impl Into<String>, profile: LoadProfile, steps: Vec<LoadStep>) -> Self {
        Self {
            name: name.into(),
            template_type: None,
            max_requests: None,
            start_delay_millis: None,
            thresholds: Vec::new(),
            abort_on_fail: false,
            abort_grace_millis: None,
            pacing: None,
            feeder: None,
            step_selection: None,
            profile,
            steps,
        }
    }

    /// Add an in-run pass/fail threshold.
    pub fn threshold(mut self, threshold: LoadThreshold) -> Self {
        self.thresholds.push(threshold);
        self
    }

    /// Set whether a FAIL verdict aborts the run early.
    pub fn abort_on_fail(mut self, abort_on_fail: bool) -> Self {
        self.abort_on_fail = abort_on_fail;
        self
    }

    /// Set the abort grace window (milliseconds) for `abort_on_fail`.
    pub fn abort_grace_millis(mut self, abort_grace_millis: u64) -> Self {
        self.abort_grace_millis = Some(abort_grace_millis);
        self
    }

    /// Set the adaptive iteration pacing.
    pub fn pacing(mut self, pacing: LoadPacing) -> Self {
        self.pacing = Some(pacing);
        self
    }

    /// Set the parameterized test data feeder.
    pub fn feeder(mut self, feeder: LoadFeeder) -> Self {
        self.feeder = Some(feeder);
        self
    }

    /// Set how each iteration selects which steps to run.
    pub fn step_selection(mut self, step_selection: LoadStepSelection) -> Self {
        self.step_selection = Some(step_selection);
        self
    }

    /// Set the template engine (`"VELOCITY"` or `"MUSTACHE"`).
    pub fn template_type(mut self, template_type: impl Into<String>) -> Self {
        self.template_type = Some(template_type.into());
        self
    }

    /// Set the hard cap on total requests dispatched.
    pub fn max_requests(mut self, max_requests: u64) -> Self {
        self.max_requests = Some(max_requests);
        self
    }

    /// Set the delay (milliseconds) before the scenario begins driving load
    /// once started.
    pub fn start_delay_millis(mut self, start_delay_millis: u64) -> Self {
        self.start_delay_millis = Some(start_delay_millis);
        self
    }
}

// ---------------------------------------------------------------------------
// SLO verdicts (PUT /mockserver/verifySLO)
// ---------------------------------------------------------------------------

/// A single service-level objective over the recorded SLI samples. Maps to the
/// `SloObjective` schema.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SloObjective {
    /// The indicator to evaluate — one of `LATENCY_P50`, `LATENCY_P95`,
    /// `LATENCY_P99`, `ERROR_RATE`.
    pub sli: String,

    /// How the observed value is compared to the threshold — one of
    /// `LESS_THAN`, `LESS_THAN_OR_EQUAL`, `GREATER_THAN`,
    /// `GREATER_THAN_OR_EQUAL`.
    pub comparator: String,

    /// The objective threshold (milliseconds for latency SLIs, a 0.0–1.0
    /// fraction for `ERROR_RATE`).
    pub threshold: f64,

    /// Which recorded traffic to evaluate — `"FORWARD"` (default) or
    /// `"INBOUND"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub scope: Option<String>,
}

impl SloObjective {
    /// Create an objective.
    pub fn new(sli: impl Into<String>, comparator: impl Into<String>, threshold: f64) -> Self {
        Self {
            sli: sli.into(),
            comparator: comparator.into(),
            threshold,
            scope: None,
        }
    }

    /// Set the evaluation scope (`"FORWARD"` or `"INBOUND"`).
    pub fn scope(mut self, scope: impl Into<String>) -> Self {
        self.scope = Some(scope.into());
        self
    }
}

/// The time window of an SLO evaluation. Maps to the `SloCriteria.window`
/// object.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct SloWindow {
    /// `"LOOKBACK"` (default) or `"EXPLICIT"`.
    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
    pub window_type: Option<String>,

    /// LOOKBACK: window length ending now.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub lookback_millis: Option<u64>,

    /// EXPLICIT: window start in epoch milliseconds.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub from_epoch_millis: Option<u64>,

    /// EXPLICIT: window end in epoch milliseconds.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub to_epoch_millis: Option<u64>,
}

impl SloWindow {
    /// A LOOKBACK window of `millis` ending now.
    pub fn lookback(millis: u64) -> Self {
        Self {
            window_type: Some("LOOKBACK".to_string()),
            lookback_millis: Some(millis),
            ..Default::default()
        }
    }

    /// An EXPLICIT window between two epoch-millisecond bounds.
    pub fn explicit(from_epoch_millis: u64, to_epoch_millis: u64) -> Self {
        Self {
            window_type: Some("EXPLICIT".to_string()),
            from_epoch_millis: Some(from_epoch_millis),
            to_epoch_millis: Some(to_epoch_millis),
            ..Default::default()
        }
    }
}

/// A named set of service-level objectives over a time window. Maps to the
/// `SloCriteria` schema (the body of `PUT /mockserver/verifySLO`).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SloCriteria {
    /// Human-readable criteria name, echoed back in the verdict.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,

    /// The time window to evaluate over.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub window: Option<SloWindow>,

    /// Minimum samples required in the window; below this the verdict is
    /// INCONCLUSIVE.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub minimum_sample_count: Option<u64>,

    /// Optional list of upstream hosts to restrict the evaluation to.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub upstream_hosts: Option<Vec<String>>,

    /// The objectives (the verdict is the logical AND of all of them).
    pub objectives: Vec<SloObjective>,
}

impl SloCriteria {
    /// Create criteria from a set of objectives.
    pub fn new(objectives: Vec<SloObjective>) -> Self {
        Self {
            name: None,
            window: None,
            minimum_sample_count: None,
            upstream_hosts: None,
            objectives,
        }
    }

    /// Set the criteria name.
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Set the evaluation window.
    pub fn window(mut self, window: SloWindow) -> Self {
        self.window = Some(window);
        self
    }

    /// Set the minimum sample count.
    pub fn minimum_sample_count(mut self, count: u64) -> Self {
        self.minimum_sample_count = Some(count);
        self
    }

    /// Restrict the evaluation to the given upstream hosts.
    pub fn upstream_hosts(mut self, hosts: Vec<String>) -> Self {
        self.upstream_hosts = Some(hosts);
        self
    }
}

/// The evaluated result of a single objective. Maps to the `SloObjectiveResult`
/// schema.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SloObjectiveResult {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sli: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub comparator: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub threshold: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub observed_value: Option<f64>,
    /// `PASS`, `FAIL` or `INCONCLUSIVE`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub detail: Option<String>,
}

/// The overall verdict of an SLO evaluation. Maps to the `SloVerdict` schema —
/// the response of `PUT /mockserver/verifySLO`.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct SloVerdict {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// `PASS`, `FAIL` or `INCONCLUSIVE`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub window_from_epoch_millis: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub window_to_epoch_millis: Option<u64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sample_count: Option<u64>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub objective_results: Vec<SloObjectiveResult>,
}

impl SloVerdict {
    /// Whether the overall verdict is `PASS`.
    pub fn is_pass(&self) -> bool {
        self.result.as_deref() == Some("PASS")
    }

    /// Whether the overall verdict is `FAIL`.
    pub fn is_fail(&self) -> bool {
        self.result.as_deref() == Some("FAIL")
    }

    /// Whether the overall verdict is `INCONCLUSIVE`.
    pub fn is_inconclusive(&self) -> bool {
        self.result.as_deref() == Some("INCONCLUSIVE")
    }
}

// ---------------------------------------------------------------------------
// Preemption (PUT/GET/DELETE /mockserver/preemption)
// ---------------------------------------------------------------------------

/// Preemption simulation parameters (all fields optional). Maps to the
/// `PreemptionRequest` schema (the body of `PUT /mockserver/preemption`).
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct PreemptionRequest {
    /// How draining is signalled — `"reject503"`, `"goaway"` or `"both"`
    /// (default).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mode: Option<String>,

    /// How long in-flight requests are allowed to drain (clamped server-side).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub drain_millis: Option<u64>,

    /// Auto-uncordon after this many milliseconds (dead-man's switch); `0`
    /// (default) means no auto-uncordon.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ttl_millis: Option<u64>,

    /// HTTP/2 GOAWAY `last_stream_id` to advertise; `-1` (default) lets the
    /// server choose.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_stream_id: Option<i64>,
}

impl PreemptionRequest {
    /// An empty request (server defaults: mode "both", default drain, no TTL).
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the signalling mode (`"reject503"`, `"goaway"` or `"both"`).
    pub fn mode(mut self, mode: impl Into<String>) -> Self {
        self.mode = Some(mode.into());
        self
    }

    /// Set the drain window in milliseconds.
    pub fn drain_millis(mut self, millis: u64) -> Self {
        self.drain_millis = Some(millis);
        self
    }

    /// Set the auto-uncordon TTL in milliseconds.
    pub fn ttl_millis(mut self, millis: u64) -> Self {
        self.ttl_millis = Some(millis);
        self
    }

    /// Set the HTTP/2 GOAWAY `last_stream_id` to advertise.
    pub fn last_stream_id(mut self, id: i64) -> Self {
        self.last_stream_id = Some(id);
        self
    }
}

/// The current cordon/drain status of the server. Maps to the
/// `PreemptionStatus` schema — the response of `PUT`/`GET /mockserver/preemption`.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub struct PreemptionStatus {
    /// `"inactive"`, `"draining"` or `"drained"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub state: Option<String>,

    /// Number of requests currently in flight.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub in_flight: Option<u64>,

    /// Milliseconds left in the drain window.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub drain_remaining_millis: Option<u64>,

    /// Active signalling mode (omitted when inactive).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mode: Option<String>,
}

// ---------------------------------------------------------------------------
// Service chaos (PUT /mockserver/serviceChaos)
// ---------------------------------------------------------------------------

/// An HTTP chaos / fault-injection profile for a host or expectation. Maps to
/// the `HttpChaosProfile` schema. Captures the commonly-used fields; the model
/// carries an `extra` map for any additional server-supported keys.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct HttpChaosProfile {
    /// HTTP error status code to return instead of the real response.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error_status: Option<u16>,

    /// Probability (0.0–1.0) that a request triggers the error.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error_probability: Option<f64>,

    /// Injected latency (a [`Delay`]).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub latency: Option<Delay>,

    /// When true, drops the TCP connection without responding.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub connection_drop: Option<bool>,

    /// Fixed seed for deterministic probabilistic outcomes.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub seed: Option<i64>,

    /// Any additional fields the server supports that are not modelled above.
    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

impl HttpChaosProfile {
    /// Create an empty chaos profile.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the error status code returned on fault.
    pub fn error_status(mut self, status: u16) -> Self {
        self.error_status = Some(status);
        self
    }

    /// Set the probability (0.0–1.0) of triggering the error.
    pub fn error_probability(mut self, probability: f64) -> Self {
        self.error_probability = Some(probability);
        self
    }

    /// Set the injected latency.
    pub fn latency(mut self, latency: Delay) -> Self {
        self.latency = Some(latency);
        self
    }

    /// Drop the TCP connection without responding.
    pub fn connection_drop(mut self, drop: bool) -> Self {
        self.connection_drop = Some(drop);
        self
    }

    /// Set the deterministic seed.
    pub fn seed(mut self, seed: i64) -> Self {
        self.seed = Some(seed);
        self
    }
}

// ---------------------------------------------------------------------------
// Chaos experiment (PUT /mockserver/chaosExperiment)
// ---------------------------------------------------------------------------

/// A single stage of a chaos experiment. Maps to a `ChaosExperiment.stages[]`
/// entry.
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ChaosStage {
    /// How long this stage runs before advancing (max 86_400_000 = 24h).
    pub duration_millis: u64,

    /// Map of host -> chaos profile to apply during this stage.
    pub profiles: HashMap<String, HttpChaosProfile>,
}

impl ChaosStage {
    /// Create a stage running for `duration_millis`.
    pub fn new(duration_millis: u64) -> Self {
        Self {
            duration_millis,
            profiles: HashMap::new(),
        }
    }

    /// Add a host -> chaos profile to apply during the stage.
    pub fn profile(mut self, host: impl Into<String>, profile: HttpChaosProfile) -> Self {
        self.profiles.insert(host.into(), profile);
        self
    }
}

/// A scheduled multi-stage chaos experiment definition. Maps to the
/// `ChaosExperiment` schema (the body of `PUT /mockserver/chaosExperiment`).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ChaosExperiment {
    /// Human-readable experiment name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,

    /// Whether to loop back to stage 0 after the last stage completes (default
    /// false). Serialized as `loop` on the wire.
    #[serde(rename = "loop", skip_serializing_if = "Option::is_none")]
    pub loop_back: Option<bool>,

    /// The ordered sequence of stages.
    pub stages: Vec<ChaosStage>,
}

impl ChaosExperiment {
    /// Create an experiment from an ordered list of stages.
    pub fn new(stages: Vec<ChaosStage>) -> Self {
        Self {
            name: None,
            loop_back: None,
            stages,
        }
    }

    /// Set the experiment name.
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Set whether the experiment loops back to the first stage.
    pub fn loop_back(mut self, loop_back: bool) -> Self {
        self.loop_back = Some(loop_back);
        self
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    #[test]
    fn test_grpc_services_deserialize_from_server_wire_shape() {
        // Mirrors the JSON array produced by `PUT /mockserver/grpc/services`
        // in mockserver-core HttpState.java (camelCase keys, full type names).
        let wire = r#"[
            {
                "name": "helloworld.Greeter",
                "methods": [
                    {
                        "name": "SayHello",
                        "inputType": "helloworld.HelloRequest",
                        "outputType": "helloworld.HelloReply",
                        "clientStreaming": false,
                        "serverStreaming": false
                    },
                    {
                        "name": "LotsOfReplies",
                        "inputType": "helloworld.HelloRequest",
                        "outputType": "helloworld.HelloReply",
                        "clientStreaming": false,
                        "serverStreaming": true
                    }
                ]
            }
        ]"#;

        let services: Vec<GrpcService> = serde_json::from_str(wire).unwrap();
        assert_eq!(services.len(), 1);
        let svc = &services[0];
        assert_eq!(svc.name, "helloworld.Greeter");
        assert_eq!(svc.methods.len(), 2);

        let unary = &svc.methods[0];
        assert_eq!(unary.name, "SayHello");
        assert_eq!(unary.input_type, "helloworld.HelloRequest");
        assert_eq!(unary.output_type, "helloworld.HelloReply");
        assert!(!unary.client_streaming);
        assert!(!unary.server_streaming);

        let server_stream = &svc.methods[1];
        assert_eq!(server_stream.name, "LotsOfReplies");
        assert!(!server_stream.client_streaming);
        assert!(server_stream.server_streaming);
    }

    #[test]
    fn test_grpc_method_serializes_with_camel_case_keys() {
        let method = GrpcMethod {
            name: "BidiChat".into(),
            input_type: "chat.Message".into(),
            output_type: "chat.Message".into(),
            client_streaming: true,
            server_streaming: true,
        };
        let value = serde_json::to_value(&method).unwrap();
        assert_eq!(value["name"], "BidiChat");
        assert_eq!(value["inputType"], "chat.Message");
        assert_eq!(value["outputType"], "chat.Message");
        assert_eq!(value["clientStreaming"], true);
        assert_eq!(value["serverStreaming"], true);
    }

    #[test]
    fn test_grpc_services_empty_array() {
        let services: Vec<GrpcService> = serde_json::from_str("[]").unwrap();
        assert!(services.is_empty());
    }

    #[test]
    fn test_grpc_service_round_trips() {
        let original = GrpcService {
            name: "helloworld.Greeter".into(),
            methods: vec![GrpcMethod {
                name: "SayHello".into(),
                input_type: "helloworld.HelloRequest".into(),
                output_type: "helloworld.HelloReply".into(),
                client_streaming: false,
                server_streaming: false,
            }],
        };
        let json = serde_json::to_string(&original).unwrap();
        let parsed: GrpcService = serde_json::from_str(&json).unwrap();
        assert_eq!(original, parsed);
    }
}