summaryrefslogtreecommitdiff
path: root/src/FundLab.Api/App.fs
blob: a77fdf5de35c39352bb75f8f4bbb2485fc04411c (plain)
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
namespace FundLab.Api

open System
open System.Globalization
open System.IO
open System.Text.Json
open FundLab.Domain
open Giraffe
open Microsoft.AspNetCore.Http
open Microsoft.Extensions.DependencyInjection
open Microsoft.FSharp.Reflection

type OptionJsonConverter() =
    inherit Newtonsoft.Json.JsonConverter()

    override _.CanConvert(objectType: Type) =
        objectType.IsGenericType
        && objectType.GetGenericTypeDefinition() = typedefof<option<_>>

    override _.WriteJson(writer: Newtonsoft.Json.JsonWriter, value: obj, serializer: Newtonsoft.Json.JsonSerializer) =
        if isNull value then
            writer.WriteNull()
        else
            let _, fields = FSharpValue.GetUnionFields(value, value.GetType())

            match fields with
            | [| inner |] -> serializer.Serialize(writer, inner)
            | _ -> writer.WriteNull()

    override _.ReadJson(reader: Newtonsoft.Json.JsonReader, objectType: Type, existingValue: obj, serializer: Newtonsoft.Json.JsonSerializer) =
        let cases = FSharpType.GetUnionCases objectType
        let innerType = objectType.GetGenericArguments().[0]

        if reader.TokenType = Newtonsoft.Json.JsonToken.Null then
            FSharpValue.MakeUnion(cases.[0], [||])
        else
            let inner = serializer.Deserialize(reader, innerType)
            let someCase = cases |> Array.find (fun case -> case.Name = "Some")
            FSharpValue.MakeUnion(someCase, [| inner |])


type EmptyPortfolioResponse =
    {
        status: string
        message: string
    }

type FundApiResponse =
    {
        id: Guid
        name: string
        currency: string
        initialCash: string
        initialUnitNav: string
        isSynthetic: bool
        availableCash: string
        reservedCash: string
        status: string
    }

type ConfirmedQuoteEvidenceResponse =
    {
        navDate: string
        nav: string
        source: string
        sourceRevision: string
        sourceCollectedAt: string
        publishedAt: string option
        sourcePayloadHash: string
        firstSeenAt: string
    }

type SubscriptionOrderDetailResponse =
    {
        id: Guid
        fundId: Guid
        fundCode: string
        amount: string
        feeAmount: string
        reservedTotal: string
        status: string
        submittedAt: string
        tradeDate: string
        confirmIdempotencyKey: string option
        pendingReason: string option
        confirmedAt: string option
        confirmedNav: string option
        confirmedNavDate: string option
        confirmedUnits: string option
        confirmedInvestedCash: string option
        confirmedResidualCash: string option
        quote: ConfirmedQuoteEvidenceResponse option
        isSynthetic: bool
    }

type FundPositionResponse =
    {
        instrumentCode: string
        units: string
        reservedUnits: string
        costCash: string
        lastConfirmedAt: string
        valuationNav: string option
        valuationNavDate: string option
        valuationCollectedAt: string option
    }

type RedemptionOrderResponse =
    {
        id: Guid
        fundId: Guid
        instrumentCode: string
        units: string
        feeAmount: string
        status: string
        submittedAt: string
        tradeDate: string
        pendingReason: string option
        confirmedAt: string option
        confirmedNav: string option
        confirmedNavDate: string option
        confirmedProceeds: string option
        confirmedCostReleased: string option
        isSynthetic: bool
    }

type FundPositionsResponse =
    {
        fundId: Guid
        availableCash: string
        reservedCash: string
        positions: FundPositionResponse list
    }

type StockTradeResponse =
    {
        id: Guid
        fundId: Guid
        instrumentCode: string
        stockName: string option
        quantity: string
        price: string
        costCash: string
        executedAt: string
        isSynthetic: bool
    }

type StockPositionResponse =
    {
        instrumentCode: string
        stockName: string option
        quantity: string
        costCash: string
        lastTradedAt: string
    }

type StockPositionsResponse =
    {
        fundId: Guid
        positions: StockPositionResponse list
    }

type StockSellResponse =
    {
        id: Guid
        fundId: Guid
        instrumentCode: string
        stockName: string option
        quantity: string
        price: string
        feeAmount: string
        proceeds: string
        executedAt: string
        isSynthetic: bool
    }

type BondTradeResponse =
    {
        id: Guid
        fundId: Guid
        instrumentCode: string
        bondName: string option
        quantity: string
        price: string
        cleanPrice: string
        accruedInterest: string
        parValue: string
        settlementDate: string
        tradeDate: string
        couponRate: string option
        valueDate: string option
        maturityDate: string option
        costCash: string
        executedAt: string
        isSynthetic: bool
    }

type BondPositionResponse =
    {
        instrumentCode: string
        bondName: string option
        quantity: string
        costCash: string
        lastTradedAt: string
    }

type BondPositionsResponse =
    {
        fundId: Guid
        positions: BondPositionResponse list
    }

type BondCashflowResponse =
    {
        id: Guid
        fundId: Guid
        instrumentCode: string
        bondName: string option
        eventType: string
        eventDate: string
        quantity: string
        amount: string
        note: string option
        isSynthetic: bool
        createdAt: string
    }

type BondCashflowsResponse =
    {
        fundId: Guid
        events: BondCashflowResponse list
    }

type BondSellResponse =
    {
        id: Guid
        fundId: Guid
        instrumentCode: string
        bondName: string option
        quantity: string
        price: string
        cleanPrice: string
        accruedInterest: string
        parValue: string
        settlementDate: string
        tradeDate: string
        feeAmount: string
        proceeds: string
        costReleased: string
        realizedPnl: string
        executedAt: string
        isSynthetic: bool
    }

type BondSellsResponse =
    {
        fundId: Guid
        sells: BondSellResponse list
    }

type BondCalendarEntryResponse =
    {
        instrumentCode: string
        bondName: string option
        eventType: string
        eventDate: string
        quantity: string
        source: string
        amount: string option
        note: string option
    }

type BondCalendarResponse =
    {
        fundId: Guid
        fromDate: string
        toDate: string
        entries: BondCalendarEntryResponse list
    }

type ValuationPositionResponse =
    {
        instrumentCode: string
        name: string option
        assetClass: string
        quantity: string
        price: string option
        priceSource: string option
        cleanPrice: string option
        accruedInterest: string option
        dirtyPrice: string option
        valueBasis: string option
        marketValue: string option
        status: string
    }

type FundValuationResponse =
    {
        fundId: Guid
        currency: string
        asOfDate: string
        cash: string
        positionsMarketValue: string
        portfolioValue: string
        pricedPositions: int
        unavailablePositions: int
        positions: ValuationPositionResponse list
    }

type MarketRefreshTargetResponse =
    {
        instrumentCode: string
        assetClass: string
        snapshotDate: string
        price: string
    }

type MarketRefreshFailureResponse =
    {
        instrumentCode: string
        assetClass: string
        reason: string
    }

type MarketRefreshResponse =
    {
        fundId: Guid
        asOfDate: string
        refreshed: MarketRefreshTargetResponse list
        failures: MarketRefreshFailureResponse list
    }

type SipPlanResponse =
    {
        id: Guid
        fundId: Guid
        instrumentCode: string
        amount: string
        frequency: string
        status: string
        anchorDate: string
        nextTradeDate: string
        lastExecutionStatus: string option
        lastExecutionDate: string option
        isSynthetic: bool
        createdAt: string
    }

type InvestmentPlanResponse =
    {
        id: Guid
        fundId: Guid
        instrumentCode: string
        amount: string
        frequency: string
        status: string
        anchorDate: string
        nextRunDate: string
        lastRunStatus: string option
        lastRunDate: string option
        isSynthetic: bool
        createdAt: string
    }

type InvestmentPlanRunOutcomeResponse =
    {
        runDate: string
        status: string
        orderId: string option
        pendingReason: string option
    }

type InvestmentPlanRunPlanResponse =
    {
        planId: Guid
        instrumentCode: string
        amount: string
        frequency: string
        runs: InvestmentPlanRunOutcomeResponse list
        nextRunDate: string
    }

type InvestmentPlanRunResponse =
    {
        fundId: Guid
        processingDate: string
        plans: InvestmentPlanRunPlanResponse list
    }

type DividendResponse =
    {
        id: Guid
        fundId: Guid
        instrumentCode: string
        navDate: string
        dps: string
        mode: string
        sourceKey: string
        status: string
        grossCash: string option
        creditedUnits: string option
        creditedInvested: string option
        orderId: string option
        pendingReason: string option
        isSynthetic: bool
        createdAt: string
    }

type RebalancePlanResponse =
    {
        id: Guid
        fundId: Guid
        targets: {| instrumentCode: string; targetPercent: string |} list
        status: string
        createdAt: string
    }

type RebalanceExecutionResponse =
    {
        planId: Guid
        runDate: string
        outcomes: {| instrumentCode: string; action: string; amount: string; status: string; orderId: string option; pendingReason: string option |} list
    }

type RebalanceExecutionRecordResponse =
    {
        planId: Guid
        runDate: string
        instrumentCode: string
        action: string
        amount: string
        status: string
        orderId: string option
        pendingReason: string option
        executedAt: string
    }

type RebalanceWeightRowResponse =
    {
        instrumentCode: string
        targetPercent: string
        currentValue: string
        currentPercent: string
        action: string
        deltaAmount: string
        deltaUnits: string option
    }

type RebalancePreviewResponse =
    {
        planId: Guid
        runDate: string
        availableCash: string
        equity: string
        rows: RebalanceWeightRowResponse list
    }

type CapitalDepositResponse =
    {
        id: Guid
        fundId: Guid
        amount: string
        note: string option
        isSynthetic: bool
        createdAt: string
    }

type FundReturnsPointResponse =
    {
        date: string
        pending: bool
        totalAssets: string option
        unitNav: string option
        cash: string
        reservedCash: string
        holdingsValue: string option
        cumulativeReturn: string option
        netExternalFlow: string
    }

type FundReturnsResponse =
    {
        fundId: Guid
        pending: bool
        dataUpdatedAt: string option
        points: FundReturnsPointResponse list
    }

type ApiErrorResponse =
    {
        error: string
        message: string
    }

type MarketDataInstrumentApiResponse =
    {
        code: string
        name: string
        fundType: string option
    }

type MarketDataSearchApiResponse =
    {
        source: string
        sourceRevision: string
        collectedAt: string
        instruments: MarketDataInstrumentApiResponse list
    }

type MarketDataObservationApiResponse =
    {
        code: string
        navDate: string
        publishedAt: string option
        nav: string
        accumulatedNav: string option
        dailyReturn: string option
        source: string
        sourceRevision: string
        sourceCollectedAt: string
        sourcePayloadHash: string
        firstSeenAt: string
        lastSeenAt: string
    }

type MarketDataNavApiResponse =
    {
        code: string
        observations: MarketDataObservationApiResponse list
    }

type MarketNavDatesApiResponse =
    {
        code: string
        dates: string list
    }

type MarketNavSeriesPointApiResponse =
    {
        navDate: string
        nav: string
        accumulatedNav: string option
    }

type MarketNavSeriesApiResponse =
    {
        code: string
        points: MarketNavSeriesPointApiResponse list
    }

/// The AKShare-backed probes the market endpoints depend on. Injected together
/// so the app stays repository-only unless a caller really wants market routes.
type MarketProbes =
    {
        NavDates: INavDateProbe
        NavSeries: INavSeriesProbe
        BondQuotes: IBondQuoteProbe
        StockQuotes: IStockQuoteProbe
        StockDaily: IStockDailyProbe
    }

type BondQuoteApiResponse =
    {
        code: string
        sourceRevision: string
        name: string option
        price: string option
        cleanPrice: string option
        accruedInterest: string option
        date: string option
        maturityDate: string option
        parValue: string option
        issuePrice: string option
        valueDate: string option
        listingDate: string option
        publishDate: string option
        payInterestDay: string option
        couponRate: string option
        couponRateExplain: string option
        bondExpireYears: string option
        rating: string option
        dataStatus: string option
        accruedInterestComputed: string option
        dirtyPrice: string option
        valuationDate: string option
    }

type StockQuoteApiResponse =
    {
        code: string
        name: string option
        price: string option
        currency: string
        market: string option
        adjust: string option
        suspended: bool option
    }

type StockDailyObservationApiResponse =
    {
        date: string
        close: string
        volume: string option
        amount: string option
    }

type StockDailyApiResponse =
    {
        code: string
        observations: StockDailyObservationApiResponse list
    }

module App =
    let addOptionFriendlyJson (services: IServiceCollection) =
        let settings =
            Newtonsoft.Json.JsonSerializerSettings(
                ContractResolver = Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver()
            )

        settings.Converters.Add(OptionJsonConverter())
        services.AddSingleton<Giraffe.Json.ISerializer>(NewtonsoftJson.Serializer settings)

    let private invariant = CultureInfo.InvariantCulture

    let private cashText (value: decimal) = value.ToString("0.00", invariant)
    let private unitNavText (value: decimal) = value.ToString("0.00000000", invariant)
    let private decimalText (value: decimal) = value.ToString("0.00000000", invariant)
    let private dateText (value: DateOnly) = value.ToString("yyyy-MM-dd", invariant)
    let private timestampText (value: DateTimeOffset) = value.ToString("O", invariant)

    let private fundResponse (fund: FundRecord) : FundApiResponse =
        {
            id = fund.Id
            name = fund.Name
            currency = fund.Currency
            initialCash = cashText fund.InitialCash
            initialUnitNav = unitNavText fund.InitialUnitNav
            isSynthetic = fund.IsSynthetic
            availableCash = cashText fund.AvailableCash
            reservedCash = cashText fund.ReservedCash
            status = fund.Status
        }

    let private orderResponse (order: SubscriptionOrderRecord) : SubscriptionOrderDetailResponse =
        let quoteEvidence =
            order.ConfirmedQuote
            |> Option.map (fun quote ->
                {
                    navDate = dateText quote.NavDate
                    nav = decimalText quote.Nav
                    source = quote.Source
                    sourceRevision = quote.Revision
                    sourceCollectedAt = timestampText quote.CollectedAt
                    publishedAt = quote.PublishedAt |> Option.map timestampText
                    sourcePayloadHash = quote.PayloadHash
                    firstSeenAt = timestampText quote.FirstSeenAt
                })

        {
            id = order.Id
            fundId = order.FundId
            fundCode = order.FundCode
            amount = cashText order.Amount
            feeAmount = cashText order.FeeAmount
            reservedTotal = cashText order.ReservedTotal
            status = order.Status
            submittedAt = timestampText order.SubmittedAt
            tradeDate = dateText order.TradeDate
            confirmIdempotencyKey = order.ConfirmIdempotencyKey
            pendingReason = order.PendingReason
            confirmedAt = order.ConfirmedAt |> Option.map timestampText
            confirmedNav = order.ConfirmedQuote |> Option.map (fun quote -> decimalText quote.Nav)
            confirmedNavDate = order.ConfirmedQuote |> Option.map (fun quote -> dateText quote.NavDate)
            confirmedUnits = order.ConfirmedUnits |> Option.map decimalText
            confirmedInvestedCash = order.ConfirmedInvestedCash |> Option.map cashText
            confirmedResidualCash = order.ConfirmedResidualCash |> Option.map cashText
            quote = quoteEvidence
            isSynthetic = order.IsSynthetic
        }

    let private redemptionResponse (order: RedemptionOrderRecord) : RedemptionOrderResponse =
        {
            id = order.Id
            fundId = order.FundId
            instrumentCode = order.InstrumentCode
            units = decimalText order.Units
            feeAmount = cashText order.FeeAmount
            status = order.Status
            submittedAt = timestampText order.SubmittedAt
            tradeDate = dateText order.TradeDate
            pendingReason = order.PendingReason
            confirmedAt = order.ConfirmedAt |> Option.map timestampText
            confirmedNav = order.ConfirmedNav |> Option.map decimalText
            confirmedNavDate = order.ConfirmedNavDate |> Option.map dateText
            confirmedProceeds = order.ConfirmedProceeds |> Option.map cashText
            confirmedCostReleased = order.ConfirmedCostReleased |> Option.map cashText
            isSynthetic = order.IsSynthetic
        }

    let private stockTradeResponse (trade: StockTradeRecord) : StockTradeResponse =
        {
            id = trade.Id
            fundId = trade.FundId
            instrumentCode = trade.InstrumentCode
            stockName = trade.StockName
            quantity = decimalText trade.Quantity
            price = decimalText trade.Price
            costCash = cashText trade.CostCash
            executedAt = timestampText trade.ExecutedAt
            isSynthetic = trade.IsSynthetic
        }

    let private stockSellResponse (sell: StockSellRecord) : StockSellResponse =
        {
            id = sell.Id
            fundId = sell.FundId
            instrumentCode = sell.InstrumentCode
            stockName = sell.StockName
            quantity = decimalText sell.Quantity
            price = decimalText sell.Price
            feeAmount = cashText sell.FeeAmount
            proceeds = cashText sell.Proceeds
            executedAt = timestampText sell.ExecutedAt
            isSynthetic = sell.IsSynthetic
        }

    let private stockPositionResponse (position: StockPositionRecord) : StockPositionResponse =
        {
            instrumentCode = position.InstrumentCode
            stockName = position.StockName
            quantity = decimalText position.Quantity
            costCash = cashText position.CostCash
            lastTradedAt = timestampText position.LastTradedAt
        }

    let private bondTradeResponse (trade: BondTradeRecord) : BondTradeResponse =
        {
            id = trade.Id
            fundId = trade.FundId
            instrumentCode = trade.InstrumentCode
            bondName = trade.BondName
            quantity = decimalText trade.Quantity
            price = decimalText trade.Price
            cleanPrice = decimalText trade.CleanPrice
            accruedInterest = decimalText trade.AccruedInterest
            parValue = decimalText trade.ParValue
            settlementDate = dateText trade.SettlementDate
            tradeDate = dateText trade.TradeDate
            couponRate = trade.CouponRate |> Option.map decimalText
            valueDate = trade.ValueDate |> Option.map dateText
            maturityDate = trade.MaturityDate |> Option.map dateText
            costCash = cashText trade.CostCash
            executedAt = timestampText trade.ExecutedAt
            isSynthetic = trade.IsSynthetic
        }

    let private bondCashflowResponse (record: BondCashflowRecord) : BondCashflowResponse =
        {
            id = record.Id
            fundId = record.FundId
            instrumentCode = record.InstrumentCode
            bondName = record.BondName
            eventType = record.EventType
            eventDate = dateText record.EventDate
            quantity = decimalText record.Quantity
            amount = cashText record.Amount
            note = record.Note
            isSynthetic = record.IsSynthetic
            createdAt = timestampText record.CreatedAt
        }

    let private bondSellResponse (record: BondSellRecord) : BondSellResponse =
        {
            id = record.Id
            fundId = record.FundId
            instrumentCode = record.InstrumentCode
            bondName = record.BondName
            quantity = decimalText record.Quantity
            price = decimalText record.Price
            cleanPrice = decimalText record.CleanPrice
            accruedInterest = decimalText record.AccruedInterest
            parValue = decimalText record.ParValue
            settlementDate = dateText record.SettlementDate
            tradeDate = dateText record.TradeDate
            feeAmount = cashText record.FeeAmount
            proceeds = cashText record.Proceeds
            costReleased = cashText record.CostReleased
            realizedPnl = cashText record.RealizedPnl
            executedAt = timestampText record.ExecutedAt
            isSynthetic = record.IsSynthetic
        }

    let private bondPositionResponse (position: BondPositionRecord) : BondPositionResponse =
        {
            instrumentCode = position.InstrumentCode
            bondName = position.BondName
            quantity = decimalText position.Quantity
            costCash = cashText position.CostCash
            lastTradedAt = timestampText position.LastTradedAt
        }

    let private capitalDepositResponse (deposit: CapitalDepositRecord) : CapitalDepositResponse =
        {
            id = deposit.Id
            fundId = deposit.FundId
            amount = cashText deposit.Amount
            note = deposit.Note
            isSynthetic = deposit.IsSynthetic
            createdAt = timestampText deposit.CreatedAt
        }

    let private sipPlanResponse (plan: SipPlanRecord) : SipPlanResponse =
        {
            id = plan.Id
            fundId = plan.FundId
            instrumentCode = plan.InstrumentCode
            amount = cashText plan.Amount
            frequency = SipPolicy.frequencyText plan.Frequency
            status = plan.Status
            anchorDate = dateText plan.AnchorDate
            nextTradeDate = dateText plan.NextTradeDate
            lastExecutionStatus = plan.LastExecutionStatus
            lastExecutionDate = plan.LastExecutionDate |> Option.map dateText
            isSynthetic = plan.IsSynthetic
            createdAt = timestampText plan.CreatedAt
        }

    let private investmentPlanResponse (plan: InvestmentPlanRecord) : InvestmentPlanResponse =
        {
            id = plan.Id
            fundId = plan.FundId
            instrumentCode = plan.InstrumentCode
            amount = cashText plan.Amount
            frequency = InvestmentPlanPolicy.frequencyText plan.Frequency
            status = plan.Status
            anchorDate = dateText plan.AnchorDate
            nextRunDate = dateText plan.NextRunDate
            lastRunStatus = plan.LastRunStatus
            lastRunDate = plan.LastRunDate |> Option.map dateText
            isSynthetic = plan.IsSynthetic
            createdAt = timestampText plan.CreatedAt
        }

    let private investmentPlanRunOutcomeResponse (outcome: InvestmentPlanRunOutcome) : InvestmentPlanRunOutcomeResponse =
        {
            runDate = dateText outcome.RunDate
            status = outcome.Status
            orderId = outcome.OrderId |> Option.map (fun id -> id.ToString("D"))
            pendingReason = outcome.PendingReason
        }

    let private investmentPlanRunPlanResponse (result: InvestmentPlanRunPlanResult) : InvestmentPlanRunPlanResponse =
        {
            planId = result.PlanId
            instrumentCode = result.InstrumentCode
            amount = cashText result.Amount
            frequency = InvestmentPlanPolicy.frequencyText result.Frequency
            runs = result.Runs |> List.map investmentPlanRunOutcomeResponse
            nextRunDate = dateText result.NextRunDate
        }

    let private investmentPlanRunResponse (result: InvestmentPlanRunResult) : InvestmentPlanRunResponse =
        {
            fundId = result.FundId
            processingDate = dateText result.ProcessingDate
            plans = result.Plans |> List.map investmentPlanRunPlanResponse
        }

    let private rebalancePlanResponse (plan: RebalancePlanRecord) : RebalancePlanResponse =
        {
            id = plan.Id
            fundId = plan.FundId
            targets =
                plan.Targets
                |> List.map (fun target ->
                    {|
                        instrumentCode = target.InstrumentCode
                        targetPercent = cashText target.TargetPercent
                    |})
            status = plan.Status
            createdAt = timestampText plan.CreatedAt
        }

    let private rebalanceExecutionResponse (result: RebalanceExecutionResult) : RebalanceExecutionResponse =
        {
            planId = result.PlanId
            runDate = dateText result.RunDate
            outcomes =
                result.Outcomes
                |> List.map (fun outcome ->
                    {|
                        instrumentCode = outcome.InstrumentCode
                        action = outcome.Action
                        amount = outcome.Amount
                        status = outcome.Status
                        orderId = outcome.OrderId |> Option.map (fun id -> id.ToString("D"))
                        pendingReason = outcome.PendingReason
                    |})
        }

    let private rebalanceExecutionRecordResponse (record: RebalanceExecutionRecord) : RebalanceExecutionRecordResponse =
        {
            planId = record.PlanId
            runDate = dateText record.RunDate
            instrumentCode = record.InstrumentCode
            action = record.Action
            amount = cashText record.Amount
            status = record.Status
            orderId = record.OrderId |> Option.map (fun id -> id.ToString("D"))
            pendingReason = record.PendingReason
            executedAt = timestampText record.ExecutedAt
        }

    let private rebalanceActionText (action: RebalancePolicy.RebalanceAction) =
        match action with
        | RebalancePolicy.Buy -> "buy"
        | RebalancePolicy.Sell -> "sell"
        | RebalancePolicy.Hold -> "hold"

    let private rebalanceWeightRowResponse (row: RebalancePolicy.RebalanceWeightRow) : RebalanceWeightRowResponse =
        {
            instrumentCode = row.InstrumentCode
            targetPercent = cashText row.TargetPercent
            currentValue = cashText row.CurrentValue
            currentPercent = cashText row.CurrentPercent
            action = rebalanceActionText row.Action
            deltaAmount = cashText row.DeltaAmount
            deltaUnits = row.DeltaUnits |> Option.map decimalText
        }

    let private rebalancePreviewResponse (preview: RebalancePreview) : RebalancePreviewResponse =
        {
            planId = preview.PlanId
            runDate = dateText preview.RunDate
            availableCash = cashText preview.AvailableCash
            equity = cashText preview.Equity
            rows = preview.Rows |> List.map rebalanceWeightRowResponse
        }

    let private errorResponse status error message : HttpHandler =
        setStatusCode status
        >=> json ({
            error = error
            message = message
        } : ApiErrorResponse)

    let private tryStringProperty (root: JsonElement) (name: string) =
        let mutable property = Unchecked.defaultof<JsonElement>

        if root.TryGetProperty(name, &property) && property.ValueKind = JsonValueKind.String then
            property.GetString() |> Option.ofObj
        else
            None

    let private tryBoolProperty (root: JsonElement) (name: string) =
        let mutable property = Unchecked.defaultof<JsonElement>

        if root.TryGetProperty(name, &property) then
            match property.ValueKind with
            | JsonValueKind.True -> Some true
            | JsonValueKind.False -> Some false
            | _ -> None
        else
            None

    let private tryDecimal (label: string) (text: string) =
        if String.IsNullOrWhiteSpace text then
            Error(sprintf "%s must be a decimal string" label)
        else
            match Decimal.TryParse(text, NumberStyles.AllowLeadingSign ||| NumberStyles.AllowDecimalPoint, invariant) with
            | true, value -> Ok value
            | false, _ -> Error(sprintf "%s must be a decimal string" label)

    let private parseFundCommand (body: string) =
        try
            use document = JsonDocument.Parse(body)
            let root = document.RootElement

            if root.ValueKind <> JsonValueKind.Object then
                Error "request body must be a JSON object"
            else
                match tryStringProperty root "name", tryStringProperty root "initialCash", tryStringProperty root "initialUnitNav", tryBoolProperty root "isSynthetic" with
                | Some name, Some initialCashText, Some initialUnitNavText, Some isSynthetic ->
                    match tryDecimal "initialCash" initialCashText, tryDecimal "initialUnitNav" initialUnitNavText with
                    | Ok initialCash, Ok initialUnitNav ->
                        Ok {
                            Name = name
                            InitialCash = initialCash
                            InitialUnitNav = initialUnitNav
                            IsSynthetic = isSynthetic
                        }
                    | Error message, _
                    | _, Error message -> Error message
                | _ ->
                    Error "name, initialCash, initialUnitNav and isSynthetic are required"
        with
        | :? JsonException -> Error "request body must be valid JSON"

    let private parseOrderCommand (body: string) =
        try
            use document = JsonDocument.Parse(body)
            let root = document.RootElement

            if root.ValueKind <> JsonValueKind.Object then
                Error "request body must be a JSON object"
            else
                match tryStringProperty root "fundCode", tryStringProperty root "amount", tryStringProperty root "feeAmount" with
                | Some fundCode, Some amountText, Some feeAmountText ->
                    match tryDecimal "amount" amountText, tryDecimal "feeAmount" feeAmountText with
                    | Ok amount, Ok feeAmount ->
                        Ok {
                            FundCode = fundCode
                            Amount = amount
                            FeeAmount = feeAmount
                        }
                    | Error message, _
                    | _, Error message -> Error message
                | _ ->
                    Error "fundCode, amount and feeAmount are required"
        with
        | :? JsonException -> Error "request body must be valid JSON"

    let private parseRedemptionCommand (body: string) =
        try
            use document = JsonDocument.Parse(body)
            let root = document.RootElement

            if root.ValueKind <> JsonValueKind.Object then
                Error "request body must be a JSON object"
            else
                match tryStringProperty root "instrumentCode", tryStringProperty root "units", tryStringProperty root "feeAmount" with
                | Some code, Some unitsText, Some feeAmountText ->
                    match tryDecimal "units" unitsText, tryDecimal "feeAmount" feeAmountText with
                    | Ok units, Ok feeAmount ->
                        Ok
                            {
                                InstrumentCode = code
                                Units = units
                                FeeAmount = feeAmount
                            }
                    | Error message, _
                    | _, Error message -> Error message
                | _ ->
                    Error "instrumentCode, units and feeAmount are required"
        with
        | :? JsonException -> Error "request body must be valid JSON"

    let private parseCapitalDepositCommand (body: string) =
        try
            use document = JsonDocument.Parse(body)
            let root = document.RootElement

            if root.ValueKind <> JsonValueKind.Object then
                Error "request body must be a JSON object"
            else
                match tryStringProperty root "amount" with
                | None -> Error "amount is required"
                | Some amountText ->
                    match tryDecimal "amount" amountText with
                    | Error message -> Error message
                    | Ok amount ->
                        Ok
                            {
                                Amount = amount
                                Note = tryStringProperty root "note"
                            }
        with
        | :? JsonException -> Error "request body must be valid JSON"

    let private parseStockTradeCommand (body: string) : Result<StockTradeCommand, string> =
        try
            use document = JsonDocument.Parse(body)
            let root = document.RootElement

            if root.ValueKind <> JsonValueKind.Object then
                Error "request body must be a JSON object"
            else
                match tryStringProperty root "instrumentCode" with
                | None -> Error "instrumentCode is required"
                | Some code ->
                    if code.Trim().Length <> 6 || not (code.Trim() |> Seq.forall Char.IsDigit) then
                        Error "instrumentCode must contain exactly six digits"
                    else
                        match tryStringProperty root "quantity" with
                        | None -> Error "quantity is required"
                        | Some quantityText ->
                            match tryDecimal "quantity" quantityText with
                            | Error message -> Error message
                            | Ok quantity ->
                                Ok
                                    {
                                        InstrumentCode = code.Trim()
                                        StockName = tryStringProperty root "stockName"
                                        Quantity = quantity
                                        Price = 0m
                                    }
        with
        | :? JsonException -> Error "request body must be valid JSON"

    let private parseStockSellCommand (body: string) : Result<StockSellCommand, string> =
        try
            use document = JsonDocument.Parse(body)
            let root = document.RootElement

            if root.ValueKind <> JsonValueKind.Object then
                Error "request body must be a JSON object"
            else
                match tryStringProperty root "instrumentCode" with
                | None -> Error "instrumentCode is required"
                | Some code ->
                    if code.Trim().Length <> 6 || not (code.Trim() |> Seq.forall Char.IsDigit) then
                        Error "instrumentCode must contain exactly six digits"
                    else
                        match tryStringProperty root "quantity" with
                        | None -> Error "quantity is required"
                        | Some quantityText ->
                            match tryDecimal "quantity" quantityText with
                            | Error message -> Error message
                            | Ok quantity ->
                                match tryStringProperty root "feeAmount" with
                                | None ->
                                    Ok
                                        {
                                            InstrumentCode = code.Trim()
                                            StockName = tryStringProperty root "stockName"
                                            Quantity = quantity
                                            Price = 0m
                                            FeeAmount = 0m
                                        }
                                | Some feeText ->
                                    match tryDecimal "feeAmount" feeText with
                                    | Error message -> Error message
                                    | Ok fee ->
                                        Ok
                                            {
                                                InstrumentCode = code.Trim()
                                                StockName = tryStringProperty root "stockName"
                                                Quantity = quantity
                                                Price = 0m
                                                FeeAmount = fee
                                            }
        with
        | :? JsonException -> Error "request body must be valid JSON"

    let private parseBondTradeCommand (body: string) : Result<BondTradeCommand, string> =
        try
            use document = JsonDocument.Parse(body)
            let root = document.RootElement

            if root.ValueKind <> JsonValueKind.Object then
                Error "request body must be a JSON object"
            else
                match tryStringProperty root "instrumentCode" with
                | None -> Error "instrumentCode is required"
                | Some code ->
                    if code.Trim().Length <> 6 || not (code.Trim() |> Seq.forall Char.IsDigit) then
                        Error "instrumentCode must contain exactly six digits"
                    else
                        match tryStringProperty root "quantity" with
                        | None -> Error "quantity is required"
                        | Some quantityText ->
                            match tryDecimal "quantity" quantityText with
                            | Error message -> Error message
                            | Ok quantity ->
                                let tradeDate =
                                    match tryStringProperty root "tradeDate" with
                                    | None -> Ok None
                                    | Some text ->
                                        match DateOnly.TryParseExact(text, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None) with
                                        | true, date -> Ok(Some date)
                                        | false, _ -> Error "tradeDate must be an ISO date (yyyy-MM-dd)"

                                match tradeDate with
                                | Error message -> Error message
                                | Ok tradeDate ->
                                    Ok
                                        {
                                            InstrumentCode = code.Trim()
                                            BondName = tryStringProperty root "bondName"
                                            Quantity = quantity
                                            Price = 0m
                                            CleanPrice = 0m
                                            AccruedInterest = 0m
                                            ParValue = 100m
                                            SettlementDate = DateOnly.FromDateTime DateTime.UtcNow
                                            CouponRate = None
                                            ValueDate = None
                                            MaturityDate = None
                                            TradeDate = tradeDate
                                        }
        with
        | :? JsonException -> Error "request body must be valid JSON"

    let private parseSipPlanCommand (body: string) : Result<SipPlanCommand, string> =
        try
            use document = JsonDocument.Parse(body)
            let root = document.RootElement

            if root.ValueKind <> JsonValueKind.Object then
                Error "request body must be a JSON object"
            else
                match tryStringProperty root "instrumentCode", tryStringProperty root "amount", tryStringProperty root "frequency" with
                | Some code, Some amountText, Some frequencyText ->
                    match tryDecimal "amount" amountText, SipPolicy.parseFrequency frequencyText with
                    | Ok amount, Some frequency ->
                        Ok
                            {
                                InstrumentCode = code
                                Amount = amount
                                Frequency = frequency
                            }
                    | Error message, _ -> Error message
                    | _, None -> Error "frequency must be one of weekly, biweekly or monthly"
                | _ ->
                    Error "instrumentCode, amount and frequency are required"
        with
        | :? JsonException -> Error "request body must be valid JSON"

    let private parseInvestmentPlanCommand (body: string) : Result<InvestmentPlanCommand, string> =
        try
            use document = JsonDocument.Parse(body)
            let root = document.RootElement

            if root.ValueKind <> JsonValueKind.Object then
                Error "request body must be a JSON object"
            else
                match tryStringProperty root "instrumentCode", tryStringProperty root "amount", tryStringProperty root "frequency" with
                | Some code, Some amountText, Some frequencyText ->
                    match tryDecimal "amount" amountText, InvestmentPlanPolicy.parseFrequency frequencyText with
                    | Ok amount, Some frequency ->
                        Ok
                            {
                                InstrumentCode = code
                                Amount = amount
                                Frequency = frequency
                            }
                    | Error message, _ -> Error message
                    | _, None -> Error "frequency must be one of daily, weekly or monthly"
                | _ ->
                    Error "instrumentCode, amount and frequency are required"
        with
        | :? JsonException -> Error "request body must be valid JSON"

    let private parseRebalancePlanCommand (body: string) =
        try
            use document = JsonDocument.Parse(body)
            let root = document.RootElement

            if root.ValueKind <> JsonValueKind.Object then
                Error "request body must be a JSON object"
            else
                let mutable mutableTargets = Unchecked.defaultof<JsonElement>

                if not (root.TryGetProperty("targets", &mutableTargets)) then
                    Error "targets is required"
                else

                    let targetsElement = mutableTargets
                    if targetsElement.ValueKind <> JsonValueKind.Array then
                        Error "targets must be an array"
                    else
                        let mutable failure = None
                        let rows = ResizeArray<RebalanceTarget>()

                        for item in targetsElement.EnumerateArray() do
                            if failure.IsNone then
                                match tryStringProperty item "instrumentCode", tryStringProperty item "targetPercent" with
                                | Some code, Some percentText ->
                                    match tryDecimal "targetPercent" percentText with
                                    | Ok percent ->
                                        let targetRow: RebalancePolicy.TargetAllocation =
                                            {
                                                RebalancePolicy.TargetAllocation.InstrumentCode = code
                                                TargetPercent = percent
                                            }

                                        rows.Add(targetRow)
                                    | Error message -> failure <- Some message
                                | _ -> failure <- Some "each target needs instrumentCode and targetPercent"

                        match failure with
                        | Some message -> Error message
                        | None -> Ok { Targets = rows |> Seq.toList }
        with
        | :? JsonException -> Error "request body must be valid JSON"

    let private parseDividendCommand (body: string) =
        try
            use document = JsonDocument.Parse(body)
            let root = document.RootElement

            if root.ValueKind <> JsonValueKind.Object then
                Error "request body must be a JSON object"
            else
                match tryStringProperty root "instrumentCode", tryStringProperty root "navDate", tryStringProperty root "dps", tryStringProperty root "mode" with
                | Some code, Some navDateText, Some dpsText, Some modeText ->
                    match tryDecimal "dps" dpsText, DividendPolicy.parseMode modeText, DateOnly.TryParseExact(navDateText, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None) with
                    | Ok dps, Some mode, (true, navDate) ->
                        Ok
                            {
                                InstrumentCode = code
                                NavDate = navDate
                                Dps = dps
                                Mode = mode
                            }
                    | Error message, _, _ -> Error message
                    | _, None, _ -> Error "mode must be cash or reinvest"
                    | _, _, (false, _) -> Error "navDate must be yyyy-MM-dd"
                | _ ->
                    Error "instrumentCode, navDate, dps and mode are required"
        with
        | :? JsonException -> Error "request body must be valid JSON"

    let private dividendResponse (record: DividendRecord) : DividendResponse =
        {
            id = record.Id
            fundId = record.FundId
            instrumentCode = record.InstrumentCode
            navDate = dateText record.NavDate
            dps = decimalText record.Dps
            mode = DividendPolicy.modeText record.Mode
            sourceKey = DividendPolicy.schemeKey record.FundId record.InstrumentCode record.NavDate record.Mode
            status = record.Status
            grossCash = record.GrossCash |> Option.map cashText
            creditedUnits = record.CreditedUnits |> Option.map decimalText
            creditedInvested = record.CreditedInvested |> Option.map cashText
            orderId = record.OrderId |> Option.map (fun id -> id.ToString("D"))
            pendingReason = record.PendingReason
            isSynthetic = record.IsSynthetic
            createdAt = timestampText record.CreatedAt
        }

    let private invokeHandler handler next ctx = handler next ctx

    let private createDividend (repository: FundRepository) (fundIdText: string) : HttpHandler =
        fun next ctx ->
            task {
                match Guid.TryParse fundIdText with
                | false, _ ->
                    return! invokeHandler (errorResponse 400 "INVALID_DIVIDEND_REQUEST" "fund id must be a UUID") next ctx
                | true, fundId ->
                    use reader = new StreamReader(ctx.Request.Body)
                    let! body = reader.ReadToEndAsync()
                    let idempotencyKey = ctx.Request.Headers["Idempotency-Key"].ToString()

                    match parseDividendCommand body with
                    | Error message ->
                        return! invokeHandler (errorResponse 400 "INVALID_DIVIDEND_REQUEST" message) next ctx
                    | Ok command ->
                        try
                            match repository.RegisterDividend(idempotencyKey, fundId, command) with
                            | DividendWriteResult.DividendCredited record
                            | DividendWriteResult.DividendReplayed record ->
                                return! invokeHandler (json (dividendResponse record)) next ctx
                            | DividendWriteResult.DividendPendingReinvest record ->
                                return! invokeHandler (json (dividendResponse record)) next ctx
                            | DividendWriteResult.DividendIdempotencyConflict ->
                                return! invokeHandler (errorResponse 409 "IDEMPOTENCY_CONFLICT" "dividend scheme already registered with a different amount") next ctx
                            | DividendWriteResult.DividendInvalid message ->
                                return! invokeHandler (errorResponse 400 "INVALID_DIVIDEND_REQUEST" message) next ctx
                            | DividendWriteResult.DividendFundNotFound ->
                                return! invokeHandler (errorResponse 404 "FUND_NOT_FOUND" "fund was not found") next ctx
                            | DividendWriteResult.DividendInstrumentNotFound ->
                                return! invokeHandler (errorResponse 404 "INSTRUMENT_NOT_FOUND" "instrument code was not found in the instrument catalog") next ctx
                            | DividendWriteResult.DividendNoHoldings ->
                                return! invokeHandler (errorResponse 409 "NO_HOLDINGS" "the instrument has no confirmed holdings to receive the dividend") next ctx
                        with _ ->
                            return! invokeHandler (errorResponse 500 "PERSISTENCE_ERROR" "dividend persistence failed") next ctx
            }

    let private getDividends (repository: FundRepository) (fundIdText: string) : HttpHandler =
        fun next ctx ->
            match Guid.TryParse fundIdText with
            | false, _ -> errorResponse 400 "INVALID_FUND_ID" "fund id must be a UUID" next ctx
            | true, fundId ->
                try
                    match repository.GetFund fundId with
                    | None -> errorResponse 404 "FUND_NOT_FOUND" "fund was not found" next ctx
                    | Some _ ->
                        let records = repository.GetDividendRecords fundId
                        json (records |> List.map dividendResponse) next ctx
                with _ ->
                    errorResponse 500 "PERSISTENCE_ERROR" "dividend persistence failed" next ctx

    let private returnsPointResponse (point: FundReturnsPoint) : FundReturnsPointResponse =
        {
            date = dateText point.Date
            pending = point.Pending
            totalAssets = point.TotalAssets |> Option.map cashText
            unitNav = point.UnitNav |> Option.map unitNavText
            cash = cashText point.Cash
            reservedCash = cashText point.ReservedCash
            holdingsValue = point.HoldingsValue |> Option.map cashText
            cumulativeReturn = point.CumulativeReturn |> Option.map cashText
            netExternalFlow = cashText point.NetExternalFlow
        }

    let private getFundReturns (repository: FundRepository) (fundIdText: string) : HttpHandler =
        fun next ctx ->
            match Guid.TryParse fundIdText with
            | false, _ -> errorResponse 400 "INVALID_FUND_ID" "fund id must be a UUID" next ctx
            | true, fundId ->
                try
                    match repository.GetFundReturns fundId with
                    | None -> errorResponse 404 "FUND_NOT_FOUND" "fund was not found" next ctx
                    | Some returns ->
                        json
                            ({
                                fundId = returns.FundId
                                pending = returns.Pending
                                dataUpdatedAt = returns.DataUpdatedAt |> Option.map timestampText
                                points = returns.Points |> List.map returnsPointResponse
                            } : FundReturnsResponse)
                            next
                            ctx
                with _ ->
                    errorResponse 500 "PERSISTENCE_ERROR" "returns persistence failed" next ctx




    let private unauthorized : HttpHandler =
        setStatusCode 401
        >=> setHttpHeader "WWW-Authenticate" "Bearer"
        >=> text "Unauthorized"

    let private requireBearer (next: HttpFunc) (ctx: HttpContext) =
        let expectedToken =
            Environment.GetEnvironmentVariable("FUND_LAB_AUTH_TOKEN")
            |> Option.ofObj
            |> Option.defaultValue ""

        let authorizationHeader = ctx.Request.Headers.Authorization.ToString()

        match Authentication.authorize expectedToken authorizationHeader with
        | AuthDecision.Authorized -> next ctx
        | AuthDecision.Unauthorized -> unauthorized next ctx

    let private health : HttpHandler =
        json ({
            service = "fund-lab-api"
            status = "ok"
        } : HealthResponse)

    let private emptyPortfolio : HttpHandler =
        json ({
             status = "empty"
             message = "尚未创建基金/尚未选择投资"
         } : EmptyPortfolioResponse)

    let private createFund (repository: FundRepository) : HttpHandler =
        fun next ctx ->
            task {
                use reader = new StreamReader(ctx.Request.Body)
                let! body = reader.ReadToEndAsync()
                let idempotencyKey = ctx.Request.Headers["Idempotency-Key"].ToString()

                match parseFundCommand body with
                | Error message ->
                    return! invokeHandler (errorResponse 400 "INVALID_FUND_REQUEST" message) next ctx
                | Ok command ->
                    try
                        match repository.CreateFund(idempotencyKey, command) with
                        | FundWriteResult.Created fund ->
                            return! invokeHandler (setStatusCode 201 >=> json (fundResponse fund)) next ctx
                        | FundWriteResult.Replayed fund ->
                            return! invokeHandler (json (fundResponse fund)) next ctx
                        | FundWriteResult.IdempotencyConflict ->
                            return! invokeHandler (errorResponse 409 "IDEMPOTENCY_CONFLICT" "idempotency key was used with a different request") next ctx
                        | FundWriteResult.Invalid message ->
                            return! invokeHandler (errorResponse 400 "INVALID_FUND_REQUEST" message) next ctx
                    with _ ->
                        return! invokeHandler (errorResponse 500 "PERSISTENCE_ERROR" "fund persistence failed") next ctx
            }

    let private getFund (repository: FundRepository) (fundIdText: string) : HttpHandler =
        fun next ctx ->
            match Guid.TryParse fundIdText with
            | false, _ -> errorResponse 400 "INVALID_FUND_ID" "fund id must be a UUID" next ctx
            | true, fundId ->
                try
                    match repository.GetFund fundId with
                    | Some fund -> json (fundResponse fund) next ctx
                    | None -> errorResponse 404 "FUND_NOT_FOUND" "fund was not found" next ctx
                with _ ->
                    errorResponse 500 "PERSISTENCE_ERROR" "fund persistence failed" next ctx

    let private createOrder (repository: FundRepository) (fundIdText: string) : HttpHandler =
        fun next ctx ->
            task {
                match Guid.TryParse fundIdText with
                | false, _ ->
                    return! invokeHandler (errorResponse 400 "INVALID_FUND_ID" "fund id must be a UUID") next ctx
                | true, fundId ->
                    use reader = new StreamReader(ctx.Request.Body)
                    let! body = reader.ReadToEndAsync()
                    let idempotencyKey = ctx.Request.Headers["Idempotency-Key"].ToString()

                    match parseOrderCommand body with
                    | Error message ->
                        return! invokeHandler (errorResponse 400 "INVALID_ORDER_REQUEST" message) next ctx
                    | Ok command ->
                        try
                            match repository.CreateSubscriptionOrder(idempotencyKey, fundId, command) with
                            | SubscriptionOrderWriteResult.OrderCreated order ->
                                return! invokeHandler (setStatusCode 201 >=> json (orderResponse order)) next ctx
                            | SubscriptionOrderWriteResult.OrderReplayed order ->
                                return! invokeHandler (json (orderResponse order)) next ctx
                            | SubscriptionOrderWriteResult.OrderIdempotencyConflict ->
                                return! invokeHandler (errorResponse 409 "IDEMPOTENCY_CONFLICT" "idempotency key was used with a different request") next ctx
                            | SubscriptionOrderWriteResult.OrderInvalid message ->
                                return! invokeHandler (errorResponse 400 "INVALID_ORDER_REQUEST" message) next ctx
                            | SubscriptionOrderWriteResult.OrderFundNotFound ->
                                return! invokeHandler (errorResponse 404 "FUND_NOT_FOUND" "fund was not found") next ctx
                            | SubscriptionOrderWriteResult.OrderInstrumentNotFound ->
                                return! invokeHandler (errorResponse 404 "INSTRUMENT_NOT_FOUND" "fund code was not found in the instrument catalog") next ctx
                            | SubscriptionOrderWriteResult.OrderInsufficientFunds ->
                                return! invokeHandler (errorResponse 409 "INSUFFICIENT_FUNDS" "available cash is not enough to reserve the amount plus fee") next ctx
                        with _ ->
                            return! invokeHandler (errorResponse 500 "PERSISTENCE_ERROR" "order persistence failed") next ctx
            }

    let private getOrders (repository: FundRepository) (fundIdText: string) : HttpHandler =
        fun next ctx ->
            match Guid.TryParse fundIdText with
            | false, _ -> errorResponse 400 "INVALID_FUND_ID" "fund id must be a UUID" next ctx
            | true, fundId ->
                try
                    match repository.GetFund fundId with
                    | None -> errorResponse 404 "FUND_NOT_FOUND" "fund was not found" next ctx
                    | Some _ ->
                        let orders = repository.GetSubscriptionOrders fundId
                        json (orders |> List.map orderResponse) next ctx
                with _ ->
                    errorResponse 500 "PERSISTENCE_ERROR" "order persistence failed" next ctx

    let private confirmOrder (repository: FundRepository) (fundIdText: string) (orderIdText: string) : HttpHandler =
        fun next ctx ->
            match Guid.TryParse fundIdText, Guid.TryParse orderIdText with
            | (false, _), _
            | _, (false, _) ->
                errorResponse 400 "INVALID_CONFIRM_REQUEST" "fund id and order id must be UUIDs" next ctx
            | (true, fundId), (true, orderId) ->
                let idempotencyKey = ctx.Request.Headers["Idempotency-Key"].ToString()

                try
                    match repository.ConfirmSubscriptionOrder(idempotencyKey, fundId, orderId) with
                    | OrderConfirmed order
                    | ConfirmReplayed order
                    | ConfirmPendingNav order -> json (orderResponse order) next ctx
                    | ConfirmIdempotencyConflict ->
                        errorResponse 409 "IDEMPOTENCY_CONFLICT" "idempotency key was used with a different request" next ctx
                    | ConfirmAlreadyConfirmed ->
                        errorResponse 409 "ORDER_ALREADY_CONFIRMED" "order was already confirmed with a different idempotency key" next ctx
                    | ConfirmOrderNotFound -> errorResponse 404 "ORDER_NOT_FOUND" "order was not found" next ctx
                    | ConfirmInvalidStatus ->
                        errorResponse 409 "ORDER_INVALID_STATUS" "order is not in a confirmable status" next ctx
                    | ConfirmInvalid message -> errorResponse 400 "INVALID_CONFIRM_REQUEST" message next ctx
                with _ ->
                    errorResponse 500 "PERSISTENCE_ERROR" "order confirmation failed" next ctx

    let private getPositions (repository: FundRepository) (fundIdText: string) : HttpHandler =
        fun next ctx ->
            match Guid.TryParse fundIdText with
            | false, _ -> errorResponse 400 "INVALID_FUND_ID" "fund id must be a UUID" next ctx
            | true, fundId ->
                try
                    match repository.GetFund fundId with
                    | None -> errorResponse 404 "FUND_NOT_FOUND" "fund was not found" next ctx
                    | Some fund ->
                        let positions: FundPositionResponse list =
                            repository.GetFundPositions fundId
                            |> List.map (fun (position: FundPositionRecord) ->
                                {
                                    instrumentCode = position.InstrumentCode
                                    units = decimalText position.Units
                                    reservedUnits = decimalText position.ReservedUnits
                                    costCash = cashText position.CostCash
                                    lastConfirmedAt = timestampText position.LastConfirmedAt
                                    valuationNav = position.ValuationNav |> Option.map decimalText
                                    valuationNavDate = position.ValuationNavDate |> Option.map dateText
                                    valuationCollectedAt = position.ValuationCollectedAt |> Option.map timestampText
                                })

                        json
                            ({
                                fundId = fund.Id
                                availableCash = cashText fund.AvailableCash
                                reservedCash = cashText fund.ReservedCash
                                positions = positions
                            } : FundPositionsResponse)
                            next
                            ctx
                with _ ->
                    errorResponse 500 "PERSISTENCE_ERROR" "position persistence failed" next ctx

    let private createRedemption (repository: FundRepository) (fundIdText: string) : HttpHandler =
        fun next ctx ->
            task {
                match Guid.TryParse fundIdText with
                | false, _ ->
                    return! invokeHandler (errorResponse 400 "INVALID_REDEMPTION_REQUEST" "fund id must be a UUID") next ctx
                | true, fundId ->
                    use reader = new StreamReader(ctx.Request.Body)
                    let! body = reader.ReadToEndAsync()
                    let idempotencyKey = ctx.Request.Headers["Idempotency-Key"].ToString()

                    match parseRedemptionCommand body with
                    | Error message ->
                        return! invokeHandler (errorResponse 400 "INVALID_REDEMPTION_REQUEST" message) next ctx
                    | Ok command ->
                        try
                            match repository.CreateRedemptionOrder(idempotencyKey, fundId, command) with
                            | RedemptionWriteResult.RedemptionCreated order ->
                                return! invokeHandler (setStatusCode 201 >=> json (redemptionResponse order)) next ctx
                            | RedemptionWriteResult.RedemptionReplayed order ->
                                return! invokeHandler (json (redemptionResponse order)) next ctx
                            | RedemptionWriteResult.RedemptionIdempotencyConflict ->
                                return! invokeHandler (errorResponse 409 "IDEMPOTENCY_CONFLICT" "idempotency key was used with a different request") next ctx
                            | RedemptionWriteResult.RedemptionInvalid message ->
                                return! invokeHandler (errorResponse 400 "INVALID_REDEMPTION_REQUEST" message) next ctx
                            | RedemptionWriteResult.RedemptionFundNotFound ->
                                return! invokeHandler (errorResponse 404 "FUND_NOT_FOUND" "fund was not found") next ctx
                            | RedemptionWriteResult.RedemptionInstrumentNotFound ->
                                return! invokeHandler (errorResponse 404 "INSTRUMENT_NOT_FOUND" "instrument code was not found in the instrument catalog") next ctx
                            | RedemptionWriteResult.RedemptionInsufficientUnits ->
                                return! invokeHandler (errorResponse 409 "INSUFFICIENT_UNITS" "available holdings are not enough for the requested redemption units") next ctx
                        with _ ->
                            return! invokeHandler (errorResponse 500 "PERSISTENCE_ERROR" "redemption persistence failed") next ctx
            }

    let private getRedemptions (repository: FundRepository) (fundIdText: string) : HttpHandler =
        fun next ctx ->
            match Guid.TryParse fundIdText with
            | false, _ -> errorResponse 400 "INVALID_FUND_ID" "fund id must be a UUID" next ctx
            | true, fundId ->
                try
                    match repository.GetFund fundId with
                    | None -> errorResponse 404 "FUND_NOT_FOUND" "fund was not found" next ctx
                    | Some _ ->
                        let orders = repository.GetRedemptionOrders fundId
                        json (orders |> List.map redemptionResponse) next ctx
                with _ ->
                    errorResponse 500 "PERSISTENCE_ERROR" "redemption persistence failed" next ctx

    let private confirmRedemption (repository: FundRepository) (fundIdText: string) (orderIdText: string) : HttpHandler =
        fun next ctx ->
            match Guid.TryParse fundIdText, Guid.TryParse orderIdText with
            | (false, _), _
            | _, (false, _) ->
                errorResponse 400 "INVALID_CONFIRM_REQUEST" "fund id and order id must be UUIDs" next ctx
            | (true, fundId), (true, orderId) ->
                let idempotencyKey = ctx.Request.Headers["Idempotency-Key"].ToString()

                try
                    match repository.ConfirmRedemptionOrder(idempotencyKey, fundId, orderId) with
                    | RedemptionConfirmed order
                    | RedemptionConfirmReplayed order
                    | RedemptionPendingNav order -> json (redemptionResponse order) next ctx
                    | RedemptionConfirmIdempotencyConflict ->
                        errorResponse 409 "IDEMPOTENCY_CONFLICT" "idempotency key was used with a different request" next ctx
                    | RedemptionAlreadyConfirmed ->
                        errorResponse 409 "ORDER_ALREADY_CONFIRMED" "order was already confirmed with a different idempotency key" next ctx
                    | RedemptionOrderNotFound -> errorResponse 404 "ORDER_NOT_FOUND" "order was not found" next ctx
                    | RedemptionInvalidStatus ->
                        errorResponse 409 "ORDER_INVALID_STATUS" "order is not in a confirmable status" next ctx
                    | RedemptionConfirmResult.RedemptionInvalid message ->
                        errorResponse 400 "INVALID_CONFIRM_REQUEST" message next ctx
                with _ ->
                    errorResponse 500 "PERSISTENCE_ERROR" "redemption confirmation failed" next ctx


    let private createCapitalDeposit (repository: FundRepository) (fundIdText: string) : HttpHandler =
        fun next ctx ->
            task {
                match Guid.TryParse fundIdText with
                | false, _ ->
                    return! invokeHandler (errorResponse 400 "INVALID_CAPITAL_REQUEST" "fund id must be a UUID") next ctx
                | true, fundId ->
                    use reader = new StreamReader(ctx.Request.Body)
                    let! body = reader.ReadToEndAsync()
                    let idempotencyKey = ctx.Request.Headers["Idempotency-Key"].ToString()

                    match parseCapitalDepositCommand body with
                    | Error message ->
                        return! invokeHandler (errorResponse 400 "INVALID_CAPITAL_REQUEST" message) next ctx
                    | Ok command ->
                        try
                            match repository.CreateCapitalDeposit(idempotencyKey, fundId, command) with
                            | CapitalDepositWriteResult.CapitalDepositCreated deposit ->
                                return! invokeHandler (setStatusCode 201 >=> json (capitalDepositResponse deposit)) next ctx
                            | CapitalDepositWriteResult.CapitalDepositReplayed deposit ->
                                return! invokeHandler (json (capitalDepositResponse deposit)) next ctx
                            | CapitalDepositWriteResult.CapitalDepositIdempotencyConflict ->
                                return! invokeHandler (errorResponse 409 "IDEMPOTENCY_CONFLICT" "idempotency key was used with a different request") next ctx
                            | CapitalDepositWriteResult.CapitalDepositInvalid message ->
                                return! invokeHandler (errorResponse 400 "INVALID_CAPITAL_REQUEST" message) next ctx
                            | CapitalDepositWriteResult.CapitalDepositFundNotFound ->
                                return! invokeHandler (errorResponse 404 "FUND_NOT_FOUND" "fund was not found") next ctx
                        with _ ->
                            return! invokeHandler (errorResponse 500 "PERSISTENCE_ERROR" "capital deposit persistence failed") next ctx
            }

    let private getCapitalDeposits (repository: FundRepository) (fundIdText: string) : HttpHandler =
        fun next ctx ->
            match Guid.TryParse fundIdText with
            | false, _ -> errorResponse 400 "INVALID_FUND_ID" "fund id must be a UUID" next ctx
            | true, fundId ->
                try
                    match repository.GetFund fundId with
                    | None -> errorResponse 404 "FUND_NOT_FOUND" "fund was not found" next ctx
                    | Some _ ->
                        let deposits = repository.GetCapitalDeposits fundId
                        json (deposits |> List.map capitalDepositResponse) next ctx
                with _ ->
                    errorResponse 500 "PERSISTENCE_ERROR" "capital deposit persistence failed" next ctx

    let private createSipPlan (repository: FundRepository) (fundIdText: string) : HttpHandler =
        fun next ctx ->
            task {
                match Guid.TryParse fundIdText with
                | false, _ ->
                    return! invokeHandler (errorResponse 400 "INVALID_SIP_REQUEST" "fund id must be a UUID") next ctx
                | true, fundId ->
                    use reader = new StreamReader(ctx.Request.Body)
                    let! body = reader.ReadToEndAsync()
                    let idempotencyKey = ctx.Request.Headers["Idempotency-Key"].ToString()

                    match parseSipPlanCommand body with
                    | Error message ->
                        return! invokeHandler (errorResponse 400 "INVALID_SIP_REQUEST" message) next ctx
                    | Ok command ->
                        try
                            match repository.CreateSipPlan(idempotencyKey, fundId, command) with
                            | SipPlanWriteResult.SipPlanCreated plan ->
                                return! invokeHandler (setStatusCode 201 >=> json (sipPlanResponse plan)) next ctx
                            | SipPlanWriteResult.SipPlanReplayed plan ->
                                return! invokeHandler (json (sipPlanResponse plan)) next ctx
                            | SipPlanWriteResult.SipPlanIdempotencyConflict ->
                                return! invokeHandler (errorResponse 409 "IDEMPOTENCY_CONFLICT" "idempotency key was used with a different request") next ctx
                            | SipPlanWriteResult.SipPlanInvalid message ->
                                return! invokeHandler (errorResponse 400 "INVALID_SIP_REQUEST" message) next ctx
                            | SipPlanWriteResult.SipPlanFundNotFound ->
                                return! invokeHandler (errorResponse 404 "FUND_NOT_FOUND" "fund was not found") next ctx
                            | SipPlanWriteResult.SipPlanInstrumentNotFound ->
                                return! invokeHandler (errorResponse 404 "INSTRUMENT_NOT_FOUND" "instrument code was not found in the instrument catalog") next ctx
                        with _ ->
                            return! invokeHandler (errorResponse 500 "PERSISTENCE_ERROR" "sip plan persistence failed") next ctx
            }

    let private getSipPlans (repository: FundRepository) (fundIdText: string) : HttpHandler =
        fun next ctx ->
            match Guid.TryParse fundIdText with
            | false, _ -> errorResponse 400 "INVALID_FUND_ID" "fund id must be a UUID" next ctx
            | true, fundId ->
                try
                    match repository.GetFund fundId with
                    | None -> errorResponse 404 "FUND_NOT_FOUND" "fund was not found" next ctx
                    | Some _ ->
                        let plans = repository.GetSipPlans fundId
                        json (plans |> List.map sipPlanResponse) next ctx
                with _ ->
                    errorResponse 500 "PERSISTENCE_ERROR" "sip plan persistence failed" next ctx

    let private setSipPlanStatus
        (repository: FundRepository)
        (targetStatus: string)
        (fundIdText: string)
        (planIdText: string)
        : HttpHandler =
        fun next ctx ->
            match Guid.TryParse fundIdText, Guid.TryParse planIdText with
            | (false, _), _
            | _, (false, _) ->
                errorResponse 400 "INVALID_SIP_REQUEST" "fund id and plan id must be UUIDs" next ctx
            | (true, fundId), (true, planId) ->
                try
                    match repository.GetFund fundId with
                    | None -> errorResponse 404 "FUND_NOT_FOUND" "fund was not found" next ctx
                    | Some _ ->
                        match repository.SetSipPlanStatus(fundId, planId, targetStatus) with
                        | SipPlanStatusResult.SipPlanStatusChanged plan -> json (sipPlanResponse plan) next ctx
                        | SipPlanStatusResult.SipPlanStatusNotFound ->
                            errorResponse 404 "PLAN_NOT_FOUND" "sip plan does not belong to this fund" next ctx
                with _ ->
                    errorResponse 500 "PERSISTENCE_ERROR" "sip plan status update failed" next ctx

    let private createInvestmentPlan (repository: FundRepository) (fundIdText: string) : HttpHandler =
        fun next ctx ->
            task {
                match Guid.TryParse fundIdText with
                | false, _ ->
                    return! invokeHandler (errorResponse 400 "INVALID_INVESTMENT_PLAN_REQUEST" "fund id must be a UUID") next ctx
                | true, fundId ->
                    use reader = new StreamReader(ctx.Request.Body)
                    let! body = reader.ReadToEndAsync()
                    let idempotencyKey = ctx.Request.Headers["Idempotency-Key"].ToString()

                    match parseInvestmentPlanCommand body with
                    | Error message ->
                        return! invokeHandler (errorResponse 400 "INVALID_INVESTMENT_PLAN_REQUEST" message) next ctx
                    | Ok command ->
                        try
                            match repository.CreateInvestmentPlan(idempotencyKey, fundId, command) with
                            | InvestmentPlanWriteResult.InvestmentPlanCreated plan ->
                                return! invokeHandler (setStatusCode 201 >=> json (investmentPlanResponse plan)) next ctx
                            | InvestmentPlanWriteResult.InvestmentPlanReplayed plan ->
                                return! invokeHandler (json (investmentPlanResponse plan)) next ctx
                            | InvestmentPlanWriteResult.InvestmentPlanIdempotencyConflict ->
                                return! invokeHandler (errorResponse 409 "IDEMPOTENCY_CONFLICT" "idempotency key was used with a different request") next ctx
                            | InvestmentPlanWriteResult.InvestmentPlanInvalid message ->
                                return! invokeHandler (errorResponse 400 "INVALID_INVESTMENT_PLAN_REQUEST" message) next ctx
                            | InvestmentPlanWriteResult.InvestmentPlanFundNotFound ->
                                return! invokeHandler (errorResponse 404 "FUND_NOT_FOUND" "fund was not found") next ctx
                            | InvestmentPlanWriteResult.InvestmentPlanInstrumentNotFound ->
                                return! invokeHandler (errorResponse 404 "INSTRUMENT_NOT_FOUND" "instrument code was not found in the instrument catalog") next ctx
                        with _ ->
                            return! invokeHandler (errorResponse 500 "PERSISTENCE_ERROR" "investment plan persistence failed") next ctx
            }

    let private getInvestmentPlans (repository: FundRepository) (fundIdText: string) : HttpHandler =
        fun next ctx ->
            match Guid.TryParse fundIdText with
            | false, _ -> errorResponse 400 "INVALID_FUND_ID" "fund id must be a UUID" next ctx
            | true, fundId ->
                try
                    match repository.GetFund fundId with
                    | None -> errorResponse 404 "FUND_NOT_FOUND" "fund was not found" next ctx
                    | Some _ ->
                        let plans = repository.GetInvestmentPlans fundId
                        json (plans |> List.map investmentPlanResponse) next ctx
                with _ ->
                    errorResponse 500 "PERSISTENCE_ERROR" "investment plan persistence failed" next ctx

    let private parseInvestmentPlanRunCommand (body: string) =
        try
            if String.IsNullOrWhiteSpace body then
                Ok None
            else
                use document = JsonDocument.Parse(body)
                let root = document.RootElement

                if root.ValueKind <> JsonValueKind.Object then
                    Error "request body must be a JSON object"
                else
                    match tryStringProperty root "processingDate" with
                    | None -> Ok None
                    | Some text ->
                        match DateOnly.TryParseExact(text, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None) with
                        | true, date -> Ok(Some date)
                        | _ -> Error "processingDate must be yyyy-MM-dd"
        with
        | :? JsonException -> Error "request body must be valid JSON"

    let private runInvestmentPlans (repository: FundRepository) (fundIdText: string) : HttpHandler =
        fun next ctx ->
            task {
                match Guid.TryParse fundIdText with
                | false, _ ->
                    return! invokeHandler (errorResponse 400 "INVALID_INVESTMENT_PLAN_REQUEST" "fund id must be a UUID") next ctx
                | true, fundId ->
                    use reader = new StreamReader(ctx.Request.Body)
                    let! body = reader.ReadToEndAsync()

                    match parseInvestmentPlanRunCommand body with
                    | Error message ->
                        return! invokeHandler (errorResponse 400 "INVALID_INVESTMENT_PLAN_REQUEST" message) next ctx
                    | Ok processingDateText ->
                        let processingDate =
                            processingDateText
                            |> Option.defaultWith (fun () -> ConfirmationPolicy.tradeDateFor DateTimeOffset.UtcNow)

                        try
                            match repository.GetFund fundId with
                            | None ->
                                return! invokeHandler (errorResponse 404 "FUND_NOT_FOUND" "fund was not found") next ctx
                            | Some _ ->
                                let result = repository.RunInvestmentPlans(fundId, processingDate)
                                return! invokeHandler (json (investmentPlanRunResponse result)) next ctx
                        with _ ->
                            return! invokeHandler (errorResponse 500 "PERSISTENCE_ERROR" "investment plan run failed") next ctx
            }

    let private parseSipAdvanceCommand (body: string) =
        try
            if String.IsNullOrWhiteSpace body then
                Ok(None, 24)
            else
                use document = JsonDocument.Parse(body)
                let root = document.RootElement

                if root.ValueKind <> JsonValueKind.Object then
                    Error "request body must be a JSON object"
                else
                    let endDate =
                        match tryStringProperty root "endDate" with
                        | None -> None
                        | Some text ->
                            match DateOnly.TryParseExact(text, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None) with
                            | true, date -> Some date
                            | _ -> failwith "endDate must be yyyy-MM-dd"

                    let limit =
                        match tryStringProperty root "limit" with
                        | None -> 24
                        | Some text ->
                            match Int32.TryParse(text, CultureInfo.InvariantCulture) with
                            | true, value when value > 0 -> value
                            | _ -> failwith "limit must be a positive integer"

                    Ok(endDate, limit)
        with
        | :? JsonException -> Error "request body must be valid JSON"

    let private sipPlanAdvanceResponse (result: SipPlanAdvanceResult) =
        {|
            planId = result.PlanId
            instrumentCode = result.InstrumentCode
            amount = cashText result.Amount
            frequency = SipPolicy.frequencyText result.Frequency
            nextTradeDate = dateText result.NextTradeDate
            executions =
                result.Executions
                |> List.map (fun outcome ->
                    {|
                        tradeDate = dateText outcome.TradeDate
                        status = outcome.Status
                        orderId = outcome.OrderId |> Option.map (fun id -> id.ToString("D"))
                        pendingReason = outcome.PendingReason
                    |})
        |}

    let private advanceSipPlans (repository: FundRepository) (fundIdText: string) : HttpHandler =
        fun next ctx ->
            task {
                match Guid.TryParse fundIdText with
                | false, _ ->
                    return! invokeHandler (errorResponse 400 "INVALID_SIP_REQUEST" "fund id must be a UUID") next ctx
                | true, fundId ->
                    use reader = new StreamReader(ctx.Request.Body)
                    let! body = reader.ReadToEndAsync()

                    match parseSipAdvanceCommand body with
                    | Error message ->
                        return! invokeHandler (errorResponse 400 "INVALID_SIP_REQUEST" message) next ctx
                    | Ok(endDateText, limit) ->
                        let endDate =
                            endDateText
                            |> Option.defaultWith (fun () -> ConfirmationPolicy.tradeDateFor DateTimeOffset.UtcNow)

                        try
                            match repository.GetFund fundId with
                            | None ->
                                return! invokeHandler (errorResponse 404 "FUND_NOT_FOUND" "fund was not found") next ctx
                            | Some _ ->
                                let advanced = repository.AdvanceSipPlans(fundId, endDate, limit)

                                return!
                                    json
                                        {|
                                            fundId = fundId
                                            endDate = dateText endDate
                                            plans = advanced.Plans |> List.map sipPlanAdvanceResponse
                                        |}
                                        next
                                        ctx
                        with _ ->
                            return! invokeHandler (errorResponse 500 "PERSISTENCE_ERROR" "sip advance failed") next ctx
            }

    let private createRebalancePlan (repository: FundRepository) (fundIdText: string) : HttpHandler =
        fun next ctx ->
            task {
                match Guid.TryParse fundIdText with
                | false, _ ->
                    return! invokeHandler (errorResponse 400 "INVALID_REBALANCE_REQUEST" "fund id must be a UUID") next ctx
                | true, fundId ->
                    use reader = new StreamReader(ctx.Request.Body)
                    let! body = reader.ReadToEndAsync()
                    let idempotencyKey = ctx.Request.Headers["Idempotency-Key"].ToString()

                    match parseRebalancePlanCommand body with
                    | Error message ->
                        return! invokeHandler (errorResponse 400 "INVALID_REBALANCE_REQUEST" message) next ctx
                    | Ok command ->
                        try
                            match repository.CreateRebalancePlan(idempotencyKey, fundId, command) with
                            | RebalanceWriteResult.RebalancePlanCreated plan ->
                                return! invokeHandler (setStatusCode 201 >=> json (rebalancePlanResponse plan)) next ctx
                            | RebalanceWriteResult.RebalancePlanReplayed plan ->
                                return! invokeHandler (json (rebalancePlanResponse plan)) next ctx
                            | RebalanceWriteResult.RebalanceIdempotencyConflict ->
                                return! invokeHandler (errorResponse 409 "IDEMPOTENCY_CONFLICT" "idempotency key was used with a different request") next ctx
                            | RebalanceWriteResult.RebalanceInvalid message ->
                                return! invokeHandler (errorResponse 400 "INVALID_REBALANCE_REQUEST" message) next ctx
                            | RebalanceWriteResult.RebalanceFundNotFound ->
                                return! invokeHandler (errorResponse 404 "FUND_NOT_FOUND" "fund was not found") next ctx
                            | RebalanceWriteResult.RebalanceInstrumentNotFound ->
                                return! invokeHandler (errorResponse 404 "INSTRUMENT_NOT_FOUND" "instrument code was not found in the instrument catalog") next ctx
                        with _ ->
                            return! invokeHandler (errorResponse 500 "PERSISTENCE_ERROR" "rebalance plan persistence failed") next ctx
            }

    let private getRebalancePlans (repository: FundRepository) (fundIdText: string) : HttpHandler =
        fun next ctx ->
            match Guid.TryParse fundIdText with
            | false, _ -> errorResponse 400 "INVALID_FUND_ID" "fund id must be a UUID" next ctx
            | true, fundId ->
                try
                    match repository.GetFund fundId with
                    | None -> errorResponse 404 "FUND_NOT_FOUND" "fund was not found" next ctx
                    | Some _ ->
                        let plans = repository.GetRebalancePlans fundId
                        json (plans |> List.map rebalancePlanResponse) next ctx
                with _ ->
                    errorResponse 500 "PERSISTENCE_ERROR" "rebalance plan persistence failed" next ctx

    let private archiveRebalancePlan (repository: FundRepository) (fundIdText: string) (planIdText: string) : HttpHandler =
        fun next ctx ->
            match Guid.TryParse fundIdText, Guid.TryParse planIdText with
            | (false, _), _
            | _, (false, _) ->
                errorResponse 400 "INVALID_REBALANCE_REQUEST" "fund id and plan id must be UUIDs" next ctx
            | (true, fundId), (true, planId) ->
                try
                    match repository.GetFund fundId with
                    | None -> errorResponse 404 "FUND_NOT_FOUND" "fund was not found" next ctx
                    | Some _ ->
                        match repository.ArchiveRebalancePlan(fundId, planId) with
                        | RebalanceArchiveResult.RebalancePlanArchived plan -> json (rebalancePlanResponse plan) next ctx
                        | RebalanceArchiveResult.RebalanceArchiveNotFound ->
                            errorResponse 404 "PLAN_NOT_FOUND" "rebalance plan does not belong to this fund" next ctx
                with _ ->
                    errorResponse 500 "PERSISTENCE_ERROR" "rebalance plan archive failed" next ctx

    let private executeRebalancePlan (repository: FundRepository) (fundIdText: string) (planIdText: string) : HttpHandler =
        fun next ctx ->
            match Guid.TryParse fundIdText, Guid.TryParse planIdText with
            | (false, _), _
            | _, (false, _) ->
                errorResponse 400 "INVALID_REBALANCE_REQUEST" "fund id and plan id must be UUIDs" next ctx
            | (true, fundId), (true, planId) ->
                try
                    match repository.GetFund fundId with
                    | None ->
                        errorResponse 404 "FUND_NOT_FOUND" "fund was not found" next ctx
                    | Some _ ->
                        match repository.ExecuteRebalancePlan planId with
                        | Error message ->
                            if message.Contains("is archived") then
                                errorResponse 409 "PLAN_ARCHIVED" "rebalance plan is archived" next ctx
                            else
                                errorResponse (if message.Contains("was not found") then 404 else 400) "INVALID_REBALANCE_REQUEST" message next ctx
                        | Ok result ->
                            if result.PlanId <> Guid.Empty && repository.GetRebalancePlans fundId |> List.exists (fun plan -> plan.Id = result.PlanId) |> not then
                                errorResponse 404 "PLAN_NOT_FOUND" "rebalance plan does not belong to this fund" next ctx
                            else
                                json (rebalanceExecutionResponse result) next ctx
                with _ ->
                    errorResponse 500 "PERSISTENCE_ERROR" "rebalance execution failed" next ctx

    let private getRebalanceExecutions (repository: FundRepository) (fundIdText: string) : HttpHandler =
        fun next ctx ->
            match Guid.TryParse fundIdText with
            | false, _ -> errorResponse 400 "INVALID_FUND_ID" "fund id must be a UUID" next ctx
            | true, fundId ->
                try
                    match repository.GetFund fundId with
                    | None -> errorResponse 404 "FUND_NOT_FOUND" "fund was not found" next ctx
                    | Some _ ->
                        let records = repository.GetRebalanceExecutions fundId
                        json (records |> List.map rebalanceExecutionRecordResponse) next ctx
                with _ ->
                    errorResponse 500 "PERSISTENCE_ERROR" "rebalance execution persistence failed" next ctx

    let private previewRebalancePlan (repository: FundRepository) (fundIdText: string) (planIdText: string) : HttpHandler =
        fun next ctx ->
            match Guid.TryParse fundIdText, Guid.TryParse planIdText with
            | (false, _), _
            | _, (false, _) ->
                errorResponse 400 "INVALID_REBALANCE_REQUEST" "fund id and plan id must be UUIDs" next ctx
            | (true, fundId), (true, planId) ->
                try
                    match repository.GetFund fundId with
                    | None -> errorResponse 404 "FUND_NOT_FOUND" "fund was not found" next ctx
                    | Some _ ->
                        if repository.GetRebalancePlans fundId |> List.exists (fun plan -> plan.Id = planId) |> not then
                            errorResponse 404 "PLAN_NOT_FOUND" "rebalance plan does not belong to this fund" next ctx
                        else
                            match repository.PreviewRebalancePlan planId with
                            | Error message ->
                                if message.Contains("is archived") then
                                    errorResponse 409 "PLAN_ARCHIVED" "rebalance plan is archived" next ctx
                                else
                                    errorResponse 400 "INVALID_REBALANCE_REQUEST" message next ctx
                            | Ok preview -> json (rebalancePreviewResponse preview) next ctx
                with _ ->
                    errorResponse 500 "PERSISTENCE_ERROR" "rebalance preview failed" next ctx

    let private marketDataError (failure: MarketDataFailure) : HttpHandler =
        let status, error, message =
            match failure with
            | InvalidMarketDataRequest message -> 400, "INVALID_MARKET_DATA_REQUEST", message
            | MarketDataCollectorUnavailable message -> 503, "MARKET_DATA_UNAVAILABLE", message
            | InvalidMarketDataPayload message -> 502, "INVALID_MARKET_DATA_PAYLOAD", message
            | MarketDataPersistenceFailure _ -> 500, "PERSISTENCE_ERROR", "market data persistence failed"

        errorResponse status error message

    let private marketDataErrorText (failure: MarketDataFailure) =
        match failure with
        | InvalidMarketDataRequest message -> message
        | MarketDataCollectorUnavailable message -> message
        | InvalidMarketDataPayload message -> message
        | MarketDataPersistenceFailure message -> message

    let private marketDataInstrumentResponse (instrument: MarketDataInstrument) =
        {
            code = instrument.Code
            name = instrument.Name
            fundType = instrument.FundType
        }

    let private marketDataSearchResponse (payload: MarketDataSearchPayload) =
        {
            source = payload.Source
            sourceRevision = payload.SourceRevision
            collectedAt = timestampText payload.CollectedAt
            instruments = payload.Instruments |> List.map marketDataInstrumentResponse
        }

    let private marketDataObservationResponse (observation: MarketDataNavRecord) =
        {
            code = observation.Code
            navDate = dateText observation.NavDate
            publishedAt = observation.PublishedAt |> Option.map timestampText
            nav = decimalText observation.Nav
            accumulatedNav = observation.AccumulatedNav |> Option.map decimalText
            dailyReturn = observation.DailyReturn |> Option.map decimalText
            source = observation.Source
            sourceRevision = observation.SourceRevision
            sourceCollectedAt = timestampText observation.SourceCollectedAt
            sourcePayloadHash = observation.SourcePayloadHash
            firstSeenAt = timestampText observation.FirstSeenAt
            lastSeenAt = timestampText observation.LastSeenAt
        }

    let private marketDataNavResponse code (observations: MarketDataNavRecord list) : MarketDataNavApiResponse =
        {
            code = code
            observations = observations |> List.map marketDataObservationResponse
        }

    let private searchInstruments (marketData: IMarketDataService) : HttpHandler =
        fun next ctx ->
            match marketData.Search(ctx.Request.Query["q"].ToString(), ctx.RequestAborted) with
            | Ok payload -> json (marketDataSearchResponse payload) next ctx
            | Error failure -> marketDataError failure next ctx

    let private refreshNav (marketData: IMarketDataService) (code: string) : HttpHandler =
        fun next ctx ->
            match marketData.RefreshNav(code, ctx.RequestAborted) with
            | Ok observations -> json (marketDataNavResponse code observations) next ctx
            | Error failure -> marketDataError failure next ctx

    let private queryDate (name: string) (ctx: HttpContext) =
        let value = ctx.Request.Query[name].ToString()

        if String.IsNullOrWhiteSpace value then
            Ok None
        else
            let mutable date = DateOnly.MinValue

            if DateOnly.TryParseExact(value, "yyyy-MM-dd", invariant, DateTimeStyles.None, &date) then
                Ok(Some date)
            else
                Error(sprintf "%s must be an ISO date" name)

    let private getNav (marketData: IMarketDataService) (code: string) : HttpHandler =
        fun next ctx ->
            match queryDate "from" ctx, queryDate "to" ctx with
            | Ok fromDate, Ok toDate ->
                match marketData.GetNav(code, fromDate, toDate) with
                | Ok observations -> json (marketDataNavResponse code observations) next ctx
                | Error failure -> marketDataError failure next ctx
            | Error message, _
            | _, Error message ->
                marketDataError (InvalidMarketDataRequest message) next ctx

    let private marketDataRoutes (marketData: IMarketDataService) =
        [
            GET >=> route "/instruments/search" >=> searchInstruments marketData
            POST >=> routef "/instruments/%s/nav/refresh" (refreshNav marketData)
            GET >=> routef "/instruments/%s/nav" (getNav marketData)
        ]

    let private getMarketNavDates (probe: INavDateProbe) : HttpHandler =
        fun next ctx ->
            let code = ctx.Request.Query["code"].ToString()

            match probe.RecentNavDates(code, 5, ctx.RequestAborted) with
            | Ok dates ->
                json ({ code = code.Trim(); dates = dates |> List.map dateText } : MarketNavDatesApiResponse) next ctx
            | Error failure -> marketDataError failure next ctx

    let private marketNavSeriesPointResponse (point: NavSeriesPoint) : MarketNavSeriesPointApiResponse =
        {
            navDate = dateText point.NavDate
            nav = decimalText point.Nav
            accumulatedNav = point.AccumulatedNav |> Option.map decimalText
        }

    let private getMarketNavSeries (probe: INavSeriesProbe) : HttpHandler =
        fun next ctx ->
            let code = ctx.Request.Query["code"].ToString()
            let limitText = ctx.Request.Query["limit"].ToString()

            let limit =
                if String.IsNullOrWhiteSpace limitText then
                    Ok 30
                else
                    match Int32.TryParse(limitText, NumberStyles.Integer, invariant) with
                    | true, value when value >= 1 && value <= 250 -> Ok value
                    | _ -> Error "limit must be an integer between 1 and 250"

            match limit with
            | Error message -> marketDataError (InvalidMarketDataRequest message) next ctx
            | Ok value ->
                match probe.RecentNavSeries(code, value, ctx.RequestAborted) with
                | Ok points ->
                    json
                        ({ code = code.Trim()
                           points = points |> List.map marketNavSeriesPointResponse }
                         : MarketNavSeriesApiResponse)
                        next
                        ctx
                | Error failure -> marketDataError failure next ctx

    let private getBondQuote (probe: IBondQuoteProbe) : HttpHandler =
        fun next ctx ->
            let code = ctx.Request.Query["code"].ToString()

            match probe.GetQuote(code, ctx.RequestAborted) with
            | Ok quote ->
                let terms = BondQuote.tryTerms quote

                let valuationDate =
                    quote.Date
                    |> Option.orElse quote.PublishDate
                    |> Option.defaultValue (DateOnly.FromDateTime DateTime.UtcNow)

                let computedAccrued = terms |> Option.map (fun value -> BondRules.accruedInterest value valuationDate)

                let dirtyPrice =
                    match quote.CleanPrice |> Option.orElse quote.Price, computedAccrued with
                    | Some clean, Some accrued -> Some(BondRules.dirtyPrice clean accrued)
                    | _ -> None

                json
                    ({ code = quote.Code
                       sourceRevision = quote.SourceRevision
                       name = quote.Name
                       price = quote.Price |> Option.map decimalText
                       cleanPrice = quote.CleanPrice |> Option.map decimalText
                       accruedInterest = quote.AccruedInterest |> Option.map decimalText
                       date = quote.Date |> Option.map dateText
                       maturityDate = quote.MaturityDate |> Option.map dateText
                       parValue = quote.ParValue |> Option.map decimalText
                       issuePrice = quote.IssuePrice |> Option.map decimalText
                       valueDate = quote.ValueDate |> Option.map dateText
                       listingDate = quote.ListingDate |> Option.map dateText
                       publishDate = quote.PublishDate |> Option.map dateText
                       payInterestDay = quote.PayInterestDay
                       couponRate = quote.CouponRate |> Option.map decimalText
                       couponRateExplain = quote.CouponRateExplain
                       bondExpireYears = quote.BondExpireYears
                       rating = quote.Rating
                       dataStatus = quote.DataStatus
                       accruedInterestComputed = computedAccrued |> Option.map decimalText
                       dirtyPrice = dirtyPrice |> Option.map decimalText
                       valuationDate = Some(dateText valuationDate) }
                     : BondQuoteApiResponse)
                    next
                    ctx
            | Error failure -> marketDataError failure next ctx

    let private getStockQuote (probe: IStockQuoteProbe) : HttpHandler =
        fun next ctx ->
            let code = ctx.Request.Query["code"].ToString()

            match probe.GetQuote(code, ctx.RequestAborted) with
            | Ok quote ->
                json
                    ({ code = quote.Code
                       name = quote.Name
                       price = quote.Price |> Option.map decimalText
                       currency = quote.Currency
                       market = quote.Market
                       adjust = quote.Adjust
                       suspended = quote.Suspended }
                     : StockQuoteApiResponse)
                    next
                    ctx
            | Error failure -> marketDataError failure next ctx

    let private stockDailyObservationResponse (observation: StockDailyObservation) : StockDailyObservationApiResponse =
        {
            date = dateText observation.BarDate
            close = decimalText observation.Close
            volume = observation.Volume |> Option.map decimalText
            amount = observation.Amount |> Option.map decimalText
        }

    let private getStockDaily (probe: IStockDailyProbe) : HttpHandler =
        fun next ctx ->
            let code = ctx.Request.Query["code"].ToString()
            let daysText = ctx.Request.Query["days"].ToString()

            let days =
                if String.IsNullOrWhiteSpace daysText then
                    Ok 5
                else
                    match Int32.TryParse(daysText, NumberStyles.Integer, invariant) with
                    | true, value when value >= 1 && value <= 30 -> Ok value
                    | _ -> Error "days must be an integer between 1 and 30"

            match days with
            | Error message -> marketDataError (InvalidMarketDataRequest message) next ctx
            | Ok value ->
                match probe.RecentDaily(code, value, ctx.RequestAborted) with
                | Ok observations ->
                    json
                        ({ code = code.Trim()
                           observations = observations |> List.map stockDailyObservationResponse }
                         : StockDailyApiResponse)
                        next
                        ctx
                | Error failure -> marketDataError failure next ctx

    let private createStockTrade (repository: FundRepository) (probes: MarketProbes option) (fundIdText: string) : HttpHandler =
        fun next ctx ->
            task {
                match Guid.TryParse fundIdText with
                | false, _ ->
                    return! invokeHandler (errorResponse 400 "INVALID_STOCK_TRADE_REQUEST" "fund id must be a UUID") next ctx
                | true, fundId ->
                    use reader = new StreamReader(ctx.Request.Body)
                    let! body = reader.ReadToEndAsync()
                    let idempotencyKey = ctx.Request.Headers["Idempotency-Key"].ToString()

                    match parseStockTradeCommand body with
                    | Error message ->
                        return! invokeHandler (errorResponse 400 "INVALID_STOCK_TRADE_REQUEST" message) next ctx
                    | Ok command ->
                        match probes with
                        | None ->
                            return! invokeHandler (marketDataError (MarketDataCollectorUnavailable "stock quote probe is not configured")) next ctx
                        | Some configured ->
                            let quoteResult = configured.StockQuotes.GetQuote(command.InstrumentCode, ctx.RequestAborted)

                            match quoteResult with
                            | Error failure ->
                                return! invokeHandler (marketDataError failure) next ctx
                            | Ok quote ->
                                match quote.Price with
                                | None ->
                                    return!
                                        invokeHandler
                                            (marketDataError (InvalidMarketDataPayload "stock quote did not include a price"))
                                            next
                                            ctx
                                | Some price ->
                                    let resolvedName =
                                        match command.StockName with
                                        | Some name when not (String.IsNullOrWhiteSpace name) -> Some name
                                        | _ ->
                                            match quote.Name with
                                            | Some name when not (String.IsNullOrWhiteSpace name) -> Some name
                                            | _ -> None

                                    let priced = { command with Price = price; StockName = resolvedName }

                                    try
                                        match repository.CreateStockTrade(idempotencyKey, fundId, priced) with
                                        | StockTradeWriteResult.StockTradeCreated trade ->
                                            return! invokeHandler (setStatusCode 201 >=> json (stockTradeResponse trade)) next ctx
                                        | StockTradeWriteResult.StockTradeReplayed trade ->
                                            return! invokeHandler (json (stockTradeResponse trade)) next ctx
                                        | StockTradeWriteResult.StockTradeIdempotencyConflict ->
                                            return! invokeHandler (errorResponse 409 "IDEMPOTENCY_CONFLICT" "idempotency key was used with a different request") next ctx
                                        | StockTradeWriteResult.StockTradeInvalid message ->
                                            return! invokeHandler (errorResponse 400 "INVALID_STOCK_TRADE_REQUEST" message) next ctx
                                        | StockTradeWriteResult.StockTradeFundNotFound ->
                                            return! invokeHandler (errorResponse 404 "FUND_NOT_FOUND" "fund was not found") next ctx
                                    with _ ->
                                        return! invokeHandler (errorResponse 500 "PERSISTENCE_ERROR" "stock trade persistence failed") next ctx
            }

    let private getStockPositions (repository: FundRepository) (fundIdText: string) : HttpHandler =
        fun next ctx ->
            match Guid.TryParse fundIdText with
            | false, _ -> errorResponse 400 "INVALID_STOCK_TRADE_REQUEST" "fund id must be a UUID" next ctx
            | true, fundId ->
                try
                    match repository.GetFund fundId with
                    | None -> errorResponse 404 "FUND_NOT_FOUND" "fund was not found" next ctx
                    | Some fund ->
                        let positions =
                            repository.GetStockPositions fundId
                            |> List.map stockPositionResponse

                        json ({ fundId = fund.Id; positions = positions } : StockPositionsResponse) next ctx
                with _ ->
                    errorResponse 500 "PERSISTENCE_ERROR" "stock position persistence failed" next ctx

    let private completeStockSell
        (repository: FundRepository)
        (fundId: Guid)
        (idempotencyKey: string)
        (command: StockSellCommand)
        next
        ctx
        =
        task {
            try
                match repository.CreateStockSell(idempotencyKey, fundId, command) with
                | StockSellWriteResult.StockSellCreated sell ->
                    return! invokeHandler (setStatusCode 201 >=> json (stockSellResponse sell)) next ctx
                | StockSellWriteResult.StockSellReplayed sell ->
                    return! invokeHandler (json (stockSellResponse sell)) next ctx
                | StockSellWriteResult.StockSellIdempotencyConflict ->
                    return! invokeHandler (errorResponse 409 "IDEMPOTENCY_CONFLICT" "idempotency key was used with a different request") next ctx
                | StockSellWriteResult.StockSellInsufficientHoldings message ->
                    return! invokeHandler (errorResponse 400 "INSUFFICIENT_STOCK_HOLDINGS" message) next ctx
                | StockSellWriteResult.StockSellInvalid message ->
                    return! invokeHandler (errorResponse 400 "INVALID_STOCK_SELL_REQUEST" message) next ctx
                | StockSellWriteResult.StockSellFundNotFound ->
                    return! invokeHandler (errorResponse 404 "FUND_NOT_FOUND" "fund was not found") next ctx
            with _ ->
                return! invokeHandler (errorResponse 500 "PERSISTENCE_ERROR" "stock sale persistence failed") next ctx
        }

    let private createStockSell (repository: FundRepository) (probes: MarketProbes option) (fundIdText: string) : HttpHandler =
        fun next ctx ->
            task {
                match Guid.TryParse fundIdText with
                | false, _ ->
                    return! invokeHandler (errorResponse 400 "INVALID_STOCK_SELL_REQUEST" "fund id must be a UUID") next ctx
                | true, fundId ->
                    use reader = new StreamReader(ctx.Request.Body)
                    let! body = reader.ReadToEndAsync()
                    let idempotencyKey = ctx.Request.Headers["Idempotency-Key"].ToString()

                    match parseStockSellCommand body with
                    | Error message ->
                        return! invokeHandler (errorResponse 400 "INVALID_STOCK_SELL_REQUEST" message) next ctx
                    | Ok command ->
                        let asOfDate = ConfirmationPolicy.eventDateFor DateTimeOffset.UtcNow

                        let snapshotPrice =
                            try
                                repository.GetLatestSnapshots(fundId, "stock", asOfDate)
                                |> Map.tryFind command.InstrumentCode
                                |> Option.map (fun snapshot -> snapshot.Price)
                            with _ ->
                                None

                        let existingName =
                            try
                                repository.GetStockPositions fundId
                                |> List.tryFind (fun position -> position.InstrumentCode = command.InstrumentCode)
                                |> Option.bind (fun position -> position.StockName)
                            with _ ->
                                None

                        let resolveName (candidate: string option) =
                            match candidate with
                            | Some name when not (String.IsNullOrWhiteSpace name) -> Some name
                            | _ -> existingName

                        match snapshotPrice with
                        | Some price ->
                            return!
                                completeStockSell
                                    repository
                                    fundId
                                    idempotencyKey
                                    { command with Price = price; StockName = resolveName command.StockName }
                                    next
                                    ctx
                        | None ->
                            match probes with
                            | None ->
                                return!
                                    invokeHandler
                                        (marketDataError (MarketDataCollectorUnavailable "stock quote probe is not configured"))
                                        next
                                        ctx
                            | Some configured ->
                                match configured.StockQuotes.GetQuote(command.InstrumentCode, ctx.RequestAborted) with
                                | Error failure -> return! invokeHandler (marketDataError failure) next ctx
                                | Ok quote ->
                                    match quote.Price with
                                    | None ->
                                        return!
                                            invokeHandler
                                                (marketDataError (InvalidMarketDataPayload "stock quote did not include a price"))
                                                next
                                                ctx
                                    | Some price ->
                                        return!
                                            completeStockSell
                                                repository
                                                fundId
                                                idempotencyKey
                                                { command with Price = price; StockName = resolveName quote.Name }
                                                next
                                                ctx
            }

    let private createBondTrade (repository: FundRepository) (probes: MarketProbes option) (fundIdText: string) : HttpHandler =
        fun next ctx ->
            task {
                match Guid.TryParse fundIdText with
                | false, _ ->
                    return! invokeHandler (errorResponse 400 "INVALID_BOND_TRADE_REQUEST" "fund id must be a UUID") next ctx
                | true, fundId ->
                    use reader = new StreamReader(ctx.Request.Body)
                    let! body = reader.ReadToEndAsync()
                    let idempotencyKey = ctx.Request.Headers["Idempotency-Key"].ToString()

                    match parseBondTradeCommand body with
                    | Error message ->
                        return! invokeHandler (errorResponse 400 "INVALID_BOND_TRADE_REQUEST" message) next ctx
                    | Ok command ->
                        match probes with
                        | None ->
                            return! invokeHandler (marketDataError (MarketDataCollectorUnavailable "bond quote probe is not configured")) next ctx
                        | Some configured ->
                            let quoteResult = configured.BondQuotes.GetQuote(command.InstrumentCode, ctx.RequestAborted)

                            match quoteResult with
                            | Error failure ->
                                return! invokeHandler (marketDataError failure) next ctx
                            | Ok quote ->
                                let terms = BondQuote.tryTerms quote
                                let cleanPrice = quote.CleanPrice |> Option.orElse quote.Price

                                match cleanPrice with
                                | None ->
                                    return!
                                        invokeHandler
                                            (marketDataError (InvalidMarketDataPayload "bond quote did not include a price"))
                                            next
                                            ctx
                                | Some clean ->
                                    let asOf =
                                        command.TradeDate
                                        |> Option.orElse quote.Date
                                        |> Option.orElse quote.PublishDate
                                        |> Option.defaultValue (DateOnly.FromDateTime DateTime.UtcNow)

                                    let computedAccrued =
                                        terms |> Option.map (fun value -> BondRules.accruedInterest value asOf)

                                    let accrued =
                                        quote.AccruedInterest |> Option.orElse computedAccrued |> Option.defaultValue 0m

                                    let dirtyPrice = BondRules.dirtyPrice clean accrued
                                    let parValue = quote.ParValue |> Option.defaultValue 100m

                                    let settlement =
                                        terms
                                        |> Option.map (fun value -> BondRules.settlementDate value asOf)
                                        |> Option.defaultValue asOf

                                    let quantityCheck =
                                        terms |> Option.map (fun value -> BondRules.validateQuantity value command.Quantity)

                                    match quantityCheck with
                                    | Some(Error message) ->
                                        return! invokeHandler (errorResponse 400 "INVALID_BOND_TRADE_REQUEST" message) next ctx
                                    | _ ->
                                        let resolvedName =
                                            match command.BondName with
                                            | Some name when not (String.IsNullOrWhiteSpace name) -> Some name
                                            | _ ->
                                                match quote.Name with
                                                | Some name when not (String.IsNullOrWhiteSpace name) -> Some name
                                                | _ -> None

                                        let priced =
                                            {
                                                command with
                                                    Price = dirtyPrice
                                                    CleanPrice = clean
                                                    AccruedInterest = accrued
                                                    ParValue = parValue
                                                    SettlementDate = settlement
                                                    CouponRate = terms |> Option.map (fun value -> value.CouponRate)
                                                    ValueDate = terms |> Option.map (fun value -> value.ValueDate)
                                                    MaturityDate = terms |> Option.map (fun value -> value.MaturityDate)
                                                    TradeDate = Some asOf
                                                    BondName = resolvedName
                                            }

                                        try
                                            match repository.CreateBondTrade(idempotencyKey, fundId, priced) with
                                            | BondTradeWriteResult.BondTradeCreated trade ->
                                                return! invokeHandler (setStatusCode 201 >=> json (bondTradeResponse trade)) next ctx
                                            | BondTradeWriteResult.BondTradeReplayed trade ->
                                                return! invokeHandler (json (bondTradeResponse trade)) next ctx
                                            | BondTradeWriteResult.BondTradeIdempotencyConflict ->
                                                return! invokeHandler (errorResponse 409 "IDEMPOTENCY_CONFLICT" "idempotency key was used with a different request") next ctx
                                            | BondTradeWriteResult.BondTradeInvalid message ->
                                                return! invokeHandler (errorResponse 400 "INVALID_BOND_TRADE_REQUEST" message) next ctx
                                            | BondTradeWriteResult.BondTradeFundNotFound ->
                                                return! invokeHandler (errorResponse 404 "FUND_NOT_FOUND" "fund was not found") next ctx
                                        with _ ->
                                            return! invokeHandler (errorResponse 500 "PERSISTENCE_ERROR" "bond trade persistence failed") next ctx
            }

    let private getBondPositions (repository: FundRepository) (fundIdText: string) : HttpHandler =
        fun next ctx ->
            match Guid.TryParse fundIdText with
            | false, _ -> errorResponse 400 "INVALID_BOND_TRADE_REQUEST" "fund id must be a UUID" next ctx
            | true, fundId ->
                try
                    match repository.GetFund fundId with
                    | None -> errorResponse 404 "FUND_NOT_FOUND" "fund was not found" next ctx
                    | Some fund ->
                        let positions =
                            repository.GetBondPositions fundId
                            |> List.map bondPositionResponse

                        json ({ fundId = fund.Id; positions = positions } : BondPositionsResponse) next ctx
                with _ ->
                    errorResponse 500 "PERSISTENCE_ERROR" "bond position persistence failed" next ctx

    let private parseBondCashflowCommand (body: string) : Result<BondCashflowCommand, string> =
        try
            use document = JsonDocument.Parse(body)
            let root = document.RootElement

            if root.ValueKind <> JsonValueKind.Object then
                Error "request body must be a JSON object"
            else
                match
                    tryStringProperty root "instrumentCode",
                    tryStringProperty root "eventType",
                    tryStringProperty root "eventDate",
                    tryStringProperty root "quantity",
                    tryStringProperty root "amount"
                    with
                | Some code, Some eventType, Some eventDateText, Some quantityText, Some amountText ->
                    if code.Trim().Length <> 6 || not (code.Trim() |> Seq.forall Char.IsDigit) then
                        Error "instrumentCode must contain exactly six digits"
                    else
                        match
                            DateOnly.TryParseExact(eventDateText, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None),
                            tryDecimal "quantity" quantityText,
                            tryDecimal "amount" amountText
                            with
                        | (true, eventDate), Ok quantity, Ok amount ->
                            Ok
                                {
                                    InstrumentCode = code.Trim()
                                    BondName = tryStringProperty root "bondName"
                                    EventType = eventType
                                    EventDate = eventDate
                                    Quantity = quantity
                                    Amount = amount
                                    Note = tryStringProperty root "note"
                                }
                        | (false, _), _, _ -> Error "eventDate must be an ISO date (yyyy-MM-dd)"
                        | _, Error message, _ -> Error message
                        | _, _, Error message -> Error message
                | _ -> Error "instrumentCode, eventType, eventDate, quantity and amount are required"
        with
        | :? JsonException -> Error "request body must be valid JSON"

    let private parseBondSellCommand (body: string) : Result<BondSellCommand, string> =
        try
            use document = JsonDocument.Parse(body)
            let root = document.RootElement

            if root.ValueKind <> JsonValueKind.Object then
                Error "request body must be a JSON object"
            else
                match tryStringProperty root "instrumentCode", tryStringProperty root "quantity" with
                | Some code, Some quantityText ->
                    if code.Trim().Length <> 6 || not (code.Trim() |> Seq.forall Char.IsDigit) then
                        Error "instrumentCode must contain exactly six digits"
                    else
                        match tryDecimal "quantity" quantityText with
                        | Error message -> Error message
                        | Ok quantity ->
                            let tradeDate =
                                match tryStringProperty root "tradeDate" with
                                | None -> Ok None
                                | Some text ->
                                    match DateOnly.TryParseExact(text, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None) with
                                    | true, date -> Ok(Some date)
                                    | false, _ -> Error "tradeDate must be an ISO date (yyyy-MM-dd)"

                            let fee =
                                match tryStringProperty root "feeAmount" with
                                | None -> Ok 0m
                                | Some text -> tryDecimal "feeAmount" text

                            match tradeDate, fee with
                            | Error message, _ -> Error message
                            | _, Error message -> Error message
                            | Ok tradeDate, Ok fee ->
                                Ok
                                    {
                                        InstrumentCode = code.Trim()
                                        BondName = tryStringProperty root "bondName"
                                        Quantity = quantity
                                        Price = 0m
                                        CleanPrice = 0m
                                        AccruedInterest = 0m
                                        ParValue = 100m
                                        SettlementDate = DateOnly.FromDateTime DateTime.UtcNow
                                        TradeDate = tradeDate
                                        FeeAmount = fee
                                    }
                | _ -> Error "instrumentCode and quantity are required"
        with
        | :? JsonException -> Error "request body must be valid JSON"

    let private createBondSell (repository: FundRepository) (probes: MarketProbes option) (fundIdText: string) : HttpHandler =
        fun next ctx ->
            task {
                match Guid.TryParse fundIdText with
                | false, _ ->
                    return! invokeHandler (errorResponse 400 "INVALID_BOND_SELL_REQUEST" "fund id must be a UUID") next ctx
                | true, fundId ->
                    use reader = new StreamReader(ctx.Request.Body)
                    let! body = reader.ReadToEndAsync()
                    let idempotencyKey = ctx.Request.Headers["Idempotency-Key"].ToString()

                    match parseBondSellCommand body with
                    | Error message ->
                        return! invokeHandler (errorResponse 400 "INVALID_BOND_SELL_REQUEST" message) next ctx
                    | Ok command ->
                        match probes with
                        | None ->
                            return! invokeHandler (marketDataError (MarketDataCollectorUnavailable "bond quote probe is not configured")) next ctx
                        | Some configured ->
                            match configured.BondQuotes.GetQuote(command.InstrumentCode, ctx.RequestAborted) with
                            | Error failure -> return! invokeHandler (marketDataError failure) next ctx
                            | Ok quote ->
                                let terms = BondQuote.tryTerms quote
                                let cleanPrice = quote.CleanPrice |> Option.orElse quote.Price

                                match cleanPrice with
                                | None ->
                                    return!
                                        invokeHandler
                                            (marketDataError (InvalidMarketDataPayload "bond quote did not include a price"))
                                            next
                                            ctx
                                | Some clean ->
                                    let asOf =
                                        command.TradeDate
                                        |> Option.orElse quote.Date
                                        |> Option.orElse quote.PublishDate
                                        |> Option.defaultValue (DateOnly.FromDateTime DateTime.UtcNow)

                                    let computedAccrued =
                                        terms |> Option.map (fun value -> BondRules.accruedInterest value asOf)

                                    let accrued =
                                        quote.AccruedInterest |> Option.orElse computedAccrued |> Option.defaultValue 0m

                                    let dirtyPrice = BondRules.dirtyPrice clean accrued
                                    let parValue = quote.ParValue |> Option.defaultValue 100m

                                    let settlement =
                                        terms
                                        |> Option.map (fun value -> BondRules.settlementDate value asOf)
                                        |> Option.defaultValue asOf

                                    let resolvedName =
                                        match command.BondName with
                                        | Some name when not (String.IsNullOrWhiteSpace name) -> Some name
                                        | _ ->
                                            match quote.Name with
                                            | Some name when not (String.IsNullOrWhiteSpace name) -> Some name
                                            | _ -> None

                                    let priced =
                                        {
                                            command with
                                                Price = dirtyPrice
                                                CleanPrice = clean
                                                AccruedInterest = accrued
                                                ParValue = parValue
                                                SettlementDate = settlement
                                                TradeDate = Some asOf
                                                BondName = resolvedName
                                        }

                                    try
                                        match repository.CreateBondSell(idempotencyKey, fundId, priced) with
                                        | BondSellWriteResult.BondSellCreated sell ->
                                            return! invokeHandler (setStatusCode 201 >=> json (bondSellResponse sell)) next ctx
                                        | BondSellWriteResult.BondSellReplayed sell ->
                                            return! invokeHandler (json (bondSellResponse sell)) next ctx
                                        | BondSellWriteResult.BondSellIdempotencyConflict ->
                                            return! invokeHandler (errorResponse 409 "IDEMPOTENCY_CONFLICT" "idempotency key was used with a different request") next ctx
                                        | BondSellWriteResult.BondSellInvalid message ->
                                            return! invokeHandler (errorResponse 400 "INVALID_BOND_SELL_REQUEST" message) next ctx
                                        | BondSellWriteResult.BondSellInsufficientHoldings message ->
                                            return! invokeHandler (errorResponse 400 "INSUFFICIENT_BOND_HOLDINGS" message) next ctx
                                        | BondSellWriteResult.BondSellFundNotFound ->
                                            return! invokeHandler (errorResponse 404 "FUND_NOT_FOUND" "fund was not found") next ctx
                                    with _ ->
                                        return! invokeHandler (errorResponse 500 "PERSISTENCE_ERROR" "bond sell persistence failed") next ctx
            }

    let private getBondSells (repository: FundRepository) (fundIdText: string) : HttpHandler =
        fun next ctx ->
            match Guid.TryParse fundIdText with
            | false, _ -> errorResponse 400 "INVALID_BOND_SELL_REQUEST" "fund id must be a UUID" next ctx
            | true, fundId ->
                try
                    match repository.GetFund fundId with
                    | None -> errorResponse 404 "FUND_NOT_FOUND" "fund was not found" next ctx
                    | Some fund ->
                        let sells =
                            repository.GetBondSells fundId |> List.map bondSellResponse

                        json ({ fundId = fund.Id; sells = sells } : BondSellsResponse) next ctx
                with _ ->
                    errorResponse 500 "PERSISTENCE_ERROR" "bond sell persistence failed" next ctx

    let private getBondCalendar (repository: FundRepository) (fundIdText: string) : HttpHandler =
        fun next ctx ->
            match Guid.TryParse fundIdText with
            | false, _ -> errorResponse 400 "INVALID_BOND_CALENDAR_REQUEST" "fund id must be a UUID" next ctx
            | true, fundId ->
                let today = DateOnly.FromDateTime DateTime.UtcNow

                let parseDate (raw: string) (fallback: DateOnly) =
                    if String.IsNullOrWhiteSpace raw then
                        fallback
                    else
                        match DateOnly.TryParseExact(raw, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None) with
                        | true, date -> date
                        | _ -> fallback

                let from = parseDate (ctx.Request.Query["from"].ToString()) today
                let toDate = parseDate (ctx.Request.Query["to"].ToString()) (today.AddYears 1)

                try
                    match repository.GetFund fundId with
                    | None -> errorResponse 404 "FUND_NOT_FOUND" "fund was not found" next ctx
                    | Some fund ->
                        let positions = repository.GetBondPositions fundId

                        let termsByCode =
                            repository.GetBondTrades fundId
                            |> List.fold
                                (fun acc trade ->
                                    match trade.ValueDate, trade.MaturityDate, trade.CouponRate with
                                    | Some valueDate, Some maturityDate, Some couponRate ->
                                        Map.add
                                            trade.InstrumentCode
                                            (BondTerms.create trade.ParValue couponRate 1 valueDate maturityDate 10m 0 0m)
                                            acc
                                    | _ -> acc)
                                Map.empty

                        let scheduled =
                            positions
                            |> List.collect (fun position ->
                                match termsByCode |> Map.tryFind position.InstrumentCode with
                                | None -> []
                                | Some terms ->
                                    let coupons =
                                        BondRules.couponSchedule terms
                                        |> List.filter (fun date ->
                                            date > terms.ValueDate
                                            && date < terms.MaturityDate
                                            && date >= from
                                            && date <= toDate)
                                        |> List.map (fun date ->
                                            {
                                                instrumentCode = position.InstrumentCode
                                                bondName = position.BondName
                                                eventType = "coupon"
                                                eventDate = dateText date
                                                quantity = decimalText position.Quantity
                                                source = "scheduled"
                                                amount = None
                                                note = None
                                            })

                                    let maturity =
                                        if terms.MaturityDate >= from && terms.MaturityDate <= toDate then
                                            [
                                                {
                                                    instrumentCode = position.InstrumentCode
                                                    bondName = position.BondName
                                                    eventType = "maturity"
                                                    eventDate = dateText terms.MaturityDate
                                                    quantity = decimalText position.Quantity
                                                    source = "scheduled"
                                                    amount = None
                                                    note = None
                                                }
                                            ]
                                        else
                                            []

                                    coupons @ maturity)

                        let recorded =
                            repository.GetBondCashflows fundId
                            |> List.filter (fun event -> event.EventDate >= from && event.EventDate <= toDate)
                            |> List.map (fun event ->
                                {
                                    instrumentCode = event.InstrumentCode
                                    bondName = event.BondName
                                    eventType = event.EventType
                                    eventDate = dateText event.EventDate
                                    quantity = decimalText event.Quantity
                                    source = "recorded"
                                    amount = Some(cashText event.Amount)
                                    note = event.Note
                                })

                        let entries =
                            (recorded @ scheduled) |> List.sortBy (fun entry -> entry.eventDate, entry.instrumentCode)

                        json
                            ({ fundId = fund.Id
                               fromDate = dateText from
                               toDate = dateText toDate
                               entries = entries }
                             : BondCalendarResponse)
                            next
                            ctx
                with _ ->
                    errorResponse 500 "PERSISTENCE_ERROR" "bond calendar failed" next ctx

    let private recordBondCashflow (repository: FundRepository) (fundIdText: string) : HttpHandler =
        fun next ctx ->
            task {
                match Guid.TryParse fundIdText with
                | false, _ ->
                    return! invokeHandler (errorResponse 400 "INVALID_BOND_CASHFLOW_REQUEST" "fund id must be a UUID") next ctx
                | true, fundId ->
                    use reader = new StreamReader(ctx.Request.Body)
                    let! body = reader.ReadToEndAsync()
                    let idempotencyKey = ctx.Request.Headers["Idempotency-Key"].ToString()

                    match parseBondCashflowCommand body with
                    | Error message ->
                        return! invokeHandler (errorResponse 400 "INVALID_BOND_CASHFLOW_REQUEST" message) next ctx
                    | Ok command ->
                        try
                            match repository.RecordBondCashflow(idempotencyKey, fundId, command) with
                            | BondCashflowWriteResult.BondCashflowCreated record ->
                                return! invokeHandler (setStatusCode 201 >=> json (bondCashflowResponse record)) next ctx
                            | BondCashflowWriteResult.BondCashflowReplayed record ->
                                return! invokeHandler (json (bondCashflowResponse record)) next ctx
                            | BondCashflowWriteResult.BondCashflowIdempotencyConflict ->
                                return!
                                    invokeHandler
                                        (errorResponse 409 "IDEMPOTENCY_CONFLICT" "idempotency key was used with a different request")
                                        next
                                        ctx
                            | BondCashflowWriteResult.BondCashflowInvalid message ->
                                return! invokeHandler (errorResponse 400 "INVALID_BOND_CASHFLOW_REQUEST" message) next ctx
                            | BondCashflowWriteResult.BondCashflowFundNotFound ->
                                return! invokeHandler (errorResponse 404 "FUND_NOT_FOUND" "fund was not found") next ctx
                            | BondCashflowWriteResult.BondCashflowPositionNotFound ->
                                return! invokeHandler (errorResponse 404 "BOND_POSITION_NOT_FOUND" "bond position was not found") next ctx
                        with _ ->
                            return! invokeHandler (errorResponse 500 "PERSISTENCE_ERROR" "bond cashflow persistence failed") next ctx
            }

    let private getBondCashflows (repository: FundRepository) (fundIdText: string) : HttpHandler =
        fun next ctx ->
            match Guid.TryParse fundIdText with
            | false, _ -> errorResponse 400 "INVALID_BOND_CASHFLOW_REQUEST" "fund id must be a UUID" next ctx
            | true, fundId ->
                try
                    match repository.GetFund fundId with
                    | None -> errorResponse 404 "FUND_NOT_FOUND" "fund was not found" next ctx
                    | Some fund ->
                        let events =
                            repository.GetBondCashflows fundId |> List.map bondCashflowResponse

                        json ({ fundId = fund.Id; events = events } : BondCashflowsResponse) next ctx
                with _ ->
                    errorResponse 500 "PERSISTENCE_ERROR" "bond cashflow persistence failed" next ctx

    /// Point-in-time valuation row. For bonds the clean snapshot price is
    /// converted to a dirty (全价) value using accrued interest as of the
    /// valuation date, so the holdings value is reproducible and never uses
    /// future coupon information. Stocks keep the legacy clean basis.
    let private valuationPositionResponse
        (assetClass: string)
        (code: string)
        (fallbackName: string option)
        (quantity: decimal)
        (accrued: decimal option)
        (parValue: decimal)
        (resolvedPrice: (string * decimal) option)
        =
        let resolvedName =
            match fallbackName with
            | Some name when not (String.IsNullOrWhiteSpace name) -> Some name
            | _ -> None

        match resolvedPrice with
        | Some(source, price) ->
            let accruedValue = accrued |> Option.defaultValue 0m
            let dirtyPrice = BondRules.dirtyPrice price accruedValue

            let marketValue =
                Decimal.Round(quantity * dirtyPrice * parValue / 100m, 2, MidpointRounding.AwayFromZero)

            { instrumentCode = code
              name = resolvedName
              assetClass = assetClass
              quantity = decimalText quantity
              price = Some(decimalText price)
              priceSource = Some source
              cleanPrice = Some(decimalText price)
              accruedInterest = accrued |> Option.map decimalText
              dirtyPrice = Some(decimalText dirtyPrice)
              valueBasis = Some(if accruedValue > 0m then "dirty" else "clean")
              marketValue = Some(cashText marketValue)
              status = "priced" }
        | None ->
            { instrumentCode = code
              name = resolvedName
              assetClass = assetClass
              quantity = decimalText quantity
              price = None
              priceSource = None
              cleanPrice = None
              accruedInterest = accrued |> Option.map decimalText
              dirtyPrice = None
              valueBasis = None
              marketValue = None
              status = "unavailable" }

    /// Price precedence for a valuation row: a persisted daily snapshot on or
    /// before the valuation date wins (it is the reproducible daily close), and
    /// a live quote is only a fallback for instruments not yet refreshed.
    let private resolveValuationPrice
        (snapshotPrice: decimal option)
        (livePrice: unit -> Result<decimal option, MarketDataFailure>)
        =
        match snapshotPrice with
        | Some price -> Some("snapshot", price)
        | None ->
            match livePrice () with
            | Ok(Some price) -> Some("live", price)
            | _ -> None

    let private getFundValuation (repository: FundRepository) (probes: MarketProbes option) (fundIdText: string) : HttpHandler =
        fun next ctx ->
            match Guid.TryParse fundIdText with
            | false, _ -> errorResponse 400 "INVALID_VALUATION_REQUEST" "fund id must be a UUID" next ctx
            | true, fundId ->
                let asOfDate =
                    let raw = ctx.Request.Query["asOfDate"].ToString()
                    if String.IsNullOrWhiteSpace raw then
                        ConfirmationPolicy.eventDateFor DateTimeOffset.UtcNow
                    else
                        match DateOnly.TryParseExact(raw, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None) with
                        | true, date -> date
                        | _ -> ConfirmationPolicy.eventDateFor DateTimeOffset.UtcNow

                try
                    match repository.GetFund fundId with
                    | None -> errorResponse 404 "FUND_NOT_FOUND" "fund was not found" next ctx
                    | Some fund ->
                        let token = ctx.RequestAborted
                        let stockSnapshots = repository.GetLatestSnapshots(fundId, "stock", asOfDate)
                        let bondSnapshots = repository.GetLatestSnapshots(fundId, "bond", asOfDate)

                        let priceOf (probe: unit -> Result<decimal option, MarketDataFailure>) =
                            if probes.IsNone then
                                Error(MarketDataCollectorUnavailable "market probes are not configured")
                            else
                                probe ()

                        let stockRows =
                            repository.GetStockPositions fundId
                            |> List.map (fun position ->
                                let snapshotPrice =
                                    stockSnapshots |> Map.tryFind position.InstrumentCode |> Option.map (fun snap -> snap.Price)

                                let resolved =
                                    resolveValuationPrice snapshotPrice (fun () ->
                                        priceOf (fun () ->
                                            probes.Value.StockQuotes.GetQuote(position.InstrumentCode, token)
                                            |> Result.map (fun quote -> quote.Price)))

                                valuationPositionResponse "stock" position.InstrumentCode position.StockName position.Quantity None 100m resolved)

                        let bondTermsByCode =
                            repository.GetBondTrades fundId
                            |> List.fold
                                (fun acc trade ->
                                    match trade.ValueDate, trade.MaturityDate, trade.CouponRate with
                                    | Some valueDate, Some maturityDate, Some couponRate ->
                                        Map.add
                                            trade.InstrumentCode
                                            (BondTerms.create trade.ParValue couponRate 1 valueDate maturityDate 10m 0 0m)
                                            acc
                                    | _ -> acc)
                                Map.empty

                        let bondRows =
                            repository.GetBondPositions fundId
                            |> List.map (fun position ->
                                let snapshotPrice =
                                    bondSnapshots |> Map.tryFind position.InstrumentCode |> Option.map (fun snap -> snap.Price)

                                let resolved =
                                    resolveValuationPrice snapshotPrice (fun () ->
                                        priceOf (fun () ->
                                            probes.Value.BondQuotes.GetQuote(position.InstrumentCode, token)
                                            |> Result.map (fun quote -> quote.CleanPrice |> Option.orElse quote.Price)))

                                let terms = bondTermsByCode |> Map.tryFind position.InstrumentCode
                                let accrued = terms |> Option.map (fun value -> BondRules.accruedInterest value asOfDate)
                                let parValue = terms |> Option.map (fun value -> value.ParValue) |> Option.defaultValue 100m

                                valuationPositionResponse
                                    "bond"
                                    position.InstrumentCode
                                    position.BondName
                                    position.Quantity
                                    accrued
                                    parValue
                                    resolved)

                        let positions = stockRows @ bondRows

                        let positionsMarketValue =
                            positions
                            |> List.sumBy (fun position ->
                                match position.marketValue with
                                | Some text -> Decimal.Parse(text, invariant)
                                | None -> 0m)

                        let unavailable =
                            positions |> List.filter (fun position -> position.status = "unavailable") |> List.length

                        let response: FundValuationResponse =
                            {
                                fundId = fund.Id
                                currency = fund.Currency
                                asOfDate = dateText asOfDate
                                cash = cashText fund.AvailableCash
                                positionsMarketValue = cashText positionsMarketValue
                                portfolioValue = cashText (fund.AvailableCash + positionsMarketValue)
                                pricedPositions = positions.Length - unavailable
                                unavailablePositions = unavailable
                                positions = positions
                            }

                        json response next ctx
                with _ ->
                    errorResponse 500 "PERSISTENCE_ERROR" "fund valuation failed" next ctx

    let private refreshFundMarketData
        (repository: FundRepository)
        (marketData: IMarketDataService option)
        (probes: MarketProbes option)
        (fundIdText: string)
        : HttpHandler =
        fun next ctx ->
            match Guid.TryParse fundIdText with
            | false, _ -> errorResponse 400 "INVALID_MARKET_REFRESH_REQUEST" "fund id must be a UUID" next ctx
            | true, fundId ->
                task {
                    match repository.GetFund fundId with
                    | None -> return! invokeHandler (errorResponse 404 "FUND_NOT_FOUND" "fund was not found") next ctx
                    | Some _ ->
                        let asOfDate =
                            let raw = ctx.Request.Query["asOfDate"].ToString()
                            if String.IsNullOrWhiteSpace raw then
                                ConfirmationPolicy.eventDateFor DateTimeOffset.UtcNow
                            else
                                match DateOnly.TryParseExact(raw, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None) with
                                | true, date -> date
                                | _ -> ConfirmationPolicy.eventDateFor DateTimeOffset.UtcNow

                        let token = ctx.RequestAborted
                        let refreshed = ResizeArray<MarketRefreshTargetResponse>()
                        let failures = ResizeArray<MarketRefreshFailureResponse>()

                        let snapshotDateOf (raw: string option) =
                            match raw with
                            | Some text ->
                                match DateOnly.TryParseExact(text, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None) with
                                | true, date when date <= asOfDate -> date
                                | _ -> asOfDate
                            | None -> asOfDate

                        // Stocks: persist the latest daily close on or before the refresh date.
                        for position in repository.GetStockPositions fundId do
                            match probes with
                            | None ->
                                failures.Add(
                                    { instrumentCode = position.InstrumentCode
                                      assetClass = "stock"
                                      reason = "market probes are not configured" }
                                )
                            | Some probeSet ->
                                match probeSet.StockDaily.RecentDaily(position.InstrumentCode, 30, token) with
                                | Error failure ->
                                    failures.Add(
                                        { instrumentCode = position.InstrumentCode
                                          assetClass = "stock"
                                          reason = marketDataErrorText failure }
                                    )
                                | Ok observations ->
                                    let latest =
                                        observations
                                        |> List.filter (fun observation -> observation.BarDate <= asOfDate)
                                        |> List.sortByDescending (fun observation -> observation.BarDate)
                                        |> List.tryHead

                                    match latest with
                                    | None ->
                                        failures.Add(
                                            { instrumentCode = position.InstrumentCode
                                              assetClass = "stock"
                                              reason = "no daily bar on or before the refresh date" }
                                        )
                                    | Some bar ->
                                        let snapshot : InstrumentSnapshotRecord =
                                            { InstrumentCode = position.InstrumentCode
                                              AssetClass = "stock"
                                              SnapshotDate = bar.BarDate
                                              Price = bar.Close
                                              Source = "akshare"
                                              SourceRevision = "stock-daily"
                                              SourceCollectedAt = DateTimeOffset.UtcNow
                                              SourcePayloadHash = sprintf "stock-daily:%s:%s" position.InstrumentCode (bar.BarDate.ToString("yyyy-MM-dd")) }

                                        repository.UpsertInstrumentSnapshots [ snapshot ]

                                        refreshed.Add(
                                            { instrumentCode = position.InstrumentCode
                                              assetClass = "stock"
                                              snapshotDate = dateText bar.BarDate
                                              price = decimalText bar.Close }
                                        )

                        // Bonds: persist the latest valuation price.
                        for position in repository.GetBondPositions fundId do
                            match probes with
                            | None ->
                                failures.Add(
                                    { instrumentCode = position.InstrumentCode
                                      assetClass = "bond"
                                      reason = "market probes are not configured" }
                                )
                            | Some probeSet ->
                                match probeSet.BondQuotes.GetQuote(position.InstrumentCode, token) with
                                | Error failure ->
                                    failures.Add(
                                        { instrumentCode = position.InstrumentCode
                                          assetClass = "bond"
                                          reason = marketDataErrorText failure }
                                    )
                                | Ok quote ->
                                    match (quote.Price |> Option.orElse quote.CleanPrice) with
                                    | None ->
                                        failures.Add(
                                            { instrumentCode = position.InstrumentCode
                                              assetClass = "bond"
                                              reason = "bond quote has no valuation price" }
                                        )
                                    | Some price ->
                                        let snapshotDate =
                                            quote.Date |> Option.map (fun date -> date.ToString("yyyy-MM-dd")) |> snapshotDateOf

                                        let snapshot : InstrumentSnapshotRecord =
                                            { InstrumentCode = position.InstrumentCode
                                              AssetClass = "bond"
                                              SnapshotDate = snapshotDate
                                              Price = price
                                              Source = "akshare"
                                              SourceRevision = "bond-quote"
                                              SourceCollectedAt = DateTimeOffset.UtcNow
                                              SourcePayloadHash = sprintf "bond-quote:%s:%s" position.InstrumentCode (snapshotDate.ToString("yyyy-MM-dd")) }

                                        repository.UpsertInstrumentSnapshots [ snapshot ]

                                        refreshed.Add(
                                            { instrumentCode = position.InstrumentCode
                                              assetClass = "bond"
                                              snapshotDate = dateText snapshotDate
                                              price = decimalText price }
                                        )

                        // Held funds: refresh their published NAV history so the
                        // fund-level NAV advances with the same date.
                        for position in repository.GetFundPositions fundId do
                            match marketData with
                            | None ->
                                failures.Add(
                                    { instrumentCode = position.InstrumentCode
                                      assetClass = "fund"
                                      reason = "market data service is not configured" }
                                )
                            | Some service ->
                                match service.RefreshNav(position.InstrumentCode, token) with
                                | Error failure ->
                                    failures.Add(
                                        { instrumentCode = position.InstrumentCode
                                          assetClass = "fund"
                                          reason = marketDataErrorText failure }
                                    )
                                | Ok observations ->
                                    let latest =
                                        observations
                                        |> List.filter (fun observation -> observation.NavDate <= asOfDate)
                                        |> List.sortByDescending (fun observation -> observation.NavDate)
                                        |> List.tryHead

                                    match latest with
                                    | None ->
                                        failures.Add(
                                            { instrumentCode = position.InstrumentCode
                                              assetClass = "fund"
                                              reason = "no nav observation on or before the refresh date" }
                                        )
                                    | Some observation ->
                                        refreshed.Add(
                                            { instrumentCode = position.InstrumentCode
                                              assetClass = "fund"
                                              snapshotDate = dateText observation.NavDate
                                              price = decimalText observation.Nav }
                                        )

                        let response: MarketRefreshResponse =
                            { fundId = fundId
                              asOfDate = dateText asOfDate
                              refreshed = refreshed |> Seq.toList
                              failures = failures |> Seq.toList }

                        return! json response next ctx
                }

    let private marketProbeRoutes (probes: MarketProbes) =
        [
            GET >=> route "/market/nav-dates" >=> getMarketNavDates probes.NavDates
            GET >=> route "/market/nav-series" >=> getMarketNavSeries probes.NavSeries
            GET >=> route "/market/bond-quote" >=> getBondQuote probes.BondQuotes
            GET >=> route "/market/stock-quote" >=> getStockQuote probes.StockQuotes
            GET >=> route "/market/stock-daily" >=> getStockDaily probes.StockDaily
        ]

    let private createApplicationInternal
        (repository: FundRepository)
        (marketData: IMarketDataService option)
        (probes: MarketProbes option)
        : HttpHandler =
        let apiRoutes =
            [
                GET >=> route "/portfolio/summary" >=> emptyPortfolio
                POST >=> route "/funds" >=> createFund repository
                POST >=> routef "/funds/%s/orders" (createOrder repository)
                GET >=> routef "/funds/%s/orders" (getOrders repository)
                POST >=> routef "/funds/%s/orders/%s/confirm" (fun (fundId, orderId) -> confirmOrder repository fundId orderId)
                POST >=> routef "/funds/%s/redemptions" (createRedemption repository)
                GET >=> routef "/funds/%s/redemptions" (getRedemptions repository)
                POST >=> routef "/funds/%s/redemptions/%s/confirm" (fun (fundId, orderId) -> confirmRedemption repository fundId orderId)
                GET >=> routef "/funds/%s/positions" (getPositions repository)
                POST >=> routef "/funds/%s/capital/deposit" (createCapitalDeposit repository)
                GET >=> routef "/funds/%s/capital/deposits" (getCapitalDeposits repository)
                POST >=> routef "/funds/%s/sip/plans" (createSipPlan repository)
                GET >=> routef "/funds/%s/sip/plans" (getSipPlans repository)
                POST >=> routef "/funds/%s/sip/advance" (advanceSipPlans repository)
                POST >=> routef "/funds/%s/sip/plans/%s/pause" (fun (fundId, planId) -> setSipPlanStatus repository "paused" fundId planId)
                POST >=> routef "/funds/%s/sip/plans/%s/resume" (fun (fundId, planId) -> setSipPlanStatus repository "active" fundId planId)
                POST >=> routef "/funds/%s/rebalance/plans" (createRebalancePlan repository)
                GET >=> routef "/funds/%s/rebalance/plans" (getRebalancePlans repository)
                POST >=> routef "/funds/%s/rebalance/plans/%s/archive" (fun (fundId, planId) -> archiveRebalancePlan repository fundId planId)
                POST >=> routef "/funds/%s/rebalance/plans/%s/execute" (fun (fundId, planId) -> executeRebalancePlan repository fundId planId)
                GET >=> routef "/funds/%s/rebalance/plans/%s/preview" (fun (fundId, planId) -> previewRebalancePlan repository fundId planId)
                GET >=> routef "/funds/%s/rebalance/executions" (getRebalanceExecutions repository)
                POST >=> routef "/funds/%s/dividends" (createDividend repository)
                GET >=> routef "/funds/%s/dividends" (getDividends repository)
                GET >=> routef "/funds/%s/returns" (getFundReturns repository)
                POST >=> routef "/funds/%s/investment-plans/run" (runInvestmentPlans repository)
                POST >=> routef "/funds/%s/investment-plans" (createInvestmentPlan repository)
                GET >=> routef "/funds/%s/investment-plans" (getInvestmentPlans repository)
                POST >=> routef "/funds/%s/stock-trades" (createStockTrade repository probes)
                POST >=> routef "/funds/%s/stock-sells" (createStockSell repository probes)
                GET >=> routef "/funds/%s/stock-positions" (getStockPositions repository)
                POST >=> routef "/funds/%s/bond-trades" (createBondTrade repository probes)
                GET >=> routef "/funds/%s/bond-positions" (getBondPositions repository)
                POST >=> routef "/funds/%s/bond-sells" (createBondSell repository probes)
                GET >=> routef "/funds/%s/bond-sells" (getBondSells repository)
                POST >=> routef "/funds/%s/bond-cashflows" (recordBondCashflow repository)
                GET >=> routef "/funds/%s/bond-cashflows" (getBondCashflows repository)
                GET >=> routef "/funds/%s/bond-calendar" (getBondCalendar repository)
                GET >=> routef "/funds/%s/valuation" (getFundValuation repository probes)
                POST >=> routef "/funds/%s/market-data/refresh" (fun fundId -> refreshFundMarketData repository marketData probes fundId)
                GET >=> routef "/funds/%s" (getFund repository)
            ]
            @ (marketData |> Option.map marketDataRoutes |> Option.defaultValue [])
            @ (probes |> Option.map marketProbeRoutes |> Option.defaultValue [])

        choose [
            GET >=> route "/health" >=> health
            subRoute "/api" (
                requireBearer
                >=> choose apiRoutes
            )
            setStatusCode 404 >=> text "Not Found"
        ]

    let createApplicationWithMarketData (repository: FundRepository) (marketData: IMarketDataService) : HttpHandler =
        createApplicationInternal repository (Some marketData) None

    let createApplicationWithProbes (repository: FundRepository) (probes: MarketProbes) : HttpHandler =
        createApplicationInternal repository None (Some probes)

    let createApplicationWithMarketDataAndProbes
        (repository: FundRepository)
        (marketData: IMarketDataService)
        (probes: MarketProbes)
        : HttpHandler =
        createApplicationInternal repository (Some marketData) (Some probes)

    let createApplication (repository: FundRepository) : HttpHandler =
        createApplicationInternal repository None None