delopay 0.20.0

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

use std::collections::BTreeMap;
use std::sync::Arc;

use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::Value;

use crate::core::encoding::{encode_segment, to_json_vec};
use crate::core::error::{DelopayError, Result};
use crate::core::models::common::Currency;
use crate::core::models::product::{
    BillingReadinessResponse, BundlePricing, ProductCategoryListResponse, ProductCategoryResponse,
    ProductDeleteResponse, ProductImageUploadResponse, ProductImportPreviewResponse,
    ProductImportRunListResponse, ProductImportRunResponse, ProductKind, ProductListResponse,
    ProductPriceInterval, ProductPriceTaxBehavior, ProductProviderCreateResponse,
    ProductProviderPushResponse, ProductProviderSyncBatchResponse, ProductProviderSyncResponse,
    ProductResolveResponse, ProductResponse, ProductSalesResponse, ProductStatus,
    ProviderAccountListResponse, ProviderArchiveAction, ProviderArchiveOutcome,
    ProviderCleanupListResponse,
};
use crate::core::models::subscription::SubscriptionItem;
use crate::http::client::{Inner, KeyPolicy};
use crate::http::multipart::{FilePart, encode_file};
use crate::http::transport::HttpMethod;

/// The header every catalogue route reads the shop from.
const PROFILE_HEADER: &str = "x-profile-id";

/// The `products` resource, obtained via [`crate::Delopay::products`].
///
/// See the [module docs](self) for the shop scoping every method takes.
#[derive(Debug, Clone)]
pub struct Products {
    inner: Arc<Inner>,
}

impl Products {
    pub(crate) fn new(inner: Arc<Inner>) -> Self {
        Self { inner }
    }

    /// Send one shop-scoped request.
    ///
    /// No catalogue route deduplicates on an `Idempotency-Key`, so none is
    /// sent, not even the client-wide default: a write is never replayed
    /// after a network error or `5xx`.
    async fn send<T: DeserializeOwned>(
        &self,
        method: HttpMethod,
        path: &str,
        profile_id: &str,
        body: Option<&[u8]>,
        query: &[(&str, String)],
    ) -> Result<T> {
        self.inner
            .request_body_keyed_with_query_and_headers(
                method,
                path,
                body,
                query,
                &[(PROFILE_HEADER, profile_id)],
                None,
            )
            .await
    }

    /// [`send`](Self::send) with a JSON body.
    async fn send_json<T: DeserializeOwned, B: Serialize>(
        &self,
        method: HttpMethod,
        path: &str,
        profile_id: &str,
        params: &B,
    ) -> Result<T> {
        let body = to_json_vec(params)?;
        self.send(method, path, profile_id, Some(&body), &[]).await
    }

    /// Upload a PNG, JPEG or WebP image to the merchant CDN.
    /// `POST /products/images`
    ///
    /// Save the returned URL as a product's `image_url` on create or update;
    /// the upload alone changes no product. `bytes` is the whole image, held
    /// in memory, and `content_type` its own MIME type (`image/png`, …).
    pub async fn upload_image(
        &self,
        profile_id: &str,
        file_name: &str,
        content_type: &str,
        bytes: &[u8],
    ) -> Result<ProductImageUploadResponse> {
        let form = encode_file(&FilePart {
            field: "file",
            file_name,
            content_type,
            bytes,
        });
        let raw = self
            .inner
            .send_raw_keyed(
                HttpMethod::Post,
                "/products/images",
                Some(&form.body),
                &[],
                None,
                KeyPolicy::BodyKeyOnly,
                &[(PROFILE_HEADER, profile_id)],
                Some(&form.content_type),
            )
            .await?;
        serde_json::from_slice(&raw).map_err(|e| DelopayError::Decode(e.to_string()))
    }

    /// Create a product together with its prices. `POST /products`
    pub async fn create(
        &self,
        profile_id: &str,
        params: &ProductCreateRequest,
    ) -> Result<ProductResponse> {
        self.send_json(HttpMethod::Post, "/products", profile_id, params)
            .await
    }

    /// One page of the shop's catalogue. `GET /products/list`
    ///
    /// Archived products are returned too unless `status` narrows them away:
    /// they are what past charges refer to. A `category_id` together with
    /// `uncategorized: true` is refused before anything is sent.
    pub async fn list(
        &self,
        profile_id: &str,
        params: &ProductListParams,
    ) -> Result<ProductListResponse> {
        if params.category_id.is_some() && params.uncategorized == Some(true) {
            return Err(DelopayError::InvalidRequest(
                "`category_id` and `uncategorized: true` ask for different products; set one"
                    .to_owned(),
            ));
        }
        self.send(
            HttpMethod::Get,
            "/products/list",
            profile_id,
            None,
            &params.to_query(),
        )
        .await
    }

    /// Find the product a name or a connector's id belongs to.
    /// `GET /products/resolve`
    ///
    /// Archived products resolve too, so a payment that references one is
    /// still attributed. No match answers 404.
    pub async fn resolve(
        &self,
        profile_id: &str,
        query: &ProductResolveQuery,
    ) -> Result<ProductResolveResponse> {
        self.send(
            HttpMethod::Get,
            "/products/resolve",
            profile_id,
            None,
            &query.to_query(),
        )
        .await
    }

    /// Retrieve one product with its prices. `GET /products/{product_id}`
    pub async fn retrieve(&self, product_id: &str, profile_id: &str) -> Result<ProductResponse> {
        self.send(
            HttpMethod::Get,
            &product_path(product_id),
            profile_id,
            None,
            &[],
        )
        .await
    }

    /// What a product sold in a window, per currency, net of the refunds
    /// credited to its lines. `GET /products/{product_id}/sales`
    ///
    /// Refunds that named no product line are not included. Needs payment
    /// read access; refused (403) to a caller limited to some connected
    /// accounts.
    pub async fn sales(
        &self,
        product_id: &str,
        profile_id: &str,
        params: &ProductSalesParams,
    ) -> Result<ProductSalesResponse> {
        let path = format!("{}/sales", product_path(product_id));
        self.send(HttpMethod::Get, &path, profile_id, None, &params.to_query())
            .await
    }

    /// Which active prices of the named recurring products can start a
    /// subscription on the shop's billing processor account, in the
    /// environment the account is in now. `GET /products/billing-readiness`
    ///
    /// `product_ids` is 1 to 100 ids, sent as one comma-separated value.
    /// Reads only. Unknown ids, one-time products and archived prices are
    /// left out of the answer.
    pub async fn billing_readiness(
        &self,
        profile_id: &str,
        product_ids: &[&str],
    ) -> Result<BillingReadinessResponse> {
        self.send(
            HttpMethod::Get,
            "/products/billing-readiness",
            profile_id,
            None,
            &[("product_ids", product_ids.join(","))],
        )
        .await
    }

    /// Change a product's name, description, image, metadata, category,
    /// add-on choice or tax category. `POST /products/{product_id}`
    ///
    /// Its kind and its prices are not editable here; see the
    /// [module docs](self).
    pub async fn update(
        &self,
        product_id: &str,
        profile_id: &str,
        params: &ProductUpdateRequest,
    ) -> Result<ProductResponse> {
        self.send_json(
            HttpMethod::Post,
            &product_path(product_id),
            profile_id,
            params,
        )
        .await
    }

    /// Take a product off sale. `POST /products/{product_id}/archive`
    ///
    /// It stays readable and keeps its prices.
    pub async fn archive(&self, product_id: &str, profile_id: &str) -> Result<ProductResponse> {
        let path = format!("{}/archive", product_path(product_id));
        self.send(HttpMethod::Post, &path, profile_id, None, &[])
            .await
    }

    /// Put an archived product back on sale.
    /// `POST /products/{product_id}/restore`
    pub async fn restore(&self, product_id: &str, profile_id: &str) -> Result<ProductResponse> {
        let path = format!("{}/restore", product_path(product_id));
        self.send(HttpMethod::Post, &path, profile_id, None, &[])
            .await
    }

    /// Mark an archived product deleted. `DELETE /products/{product_id}`
    ///
    /// Payment lines keep their own purchase snapshots, and the catalogue row
    /// remains stored. To clean up at connected accounts too, use
    /// [`delete_with_providers`](Self::delete_with_providers).
    pub async fn delete(&self, product_id: &str, profile_id: &str) -> Result<()> {
        // Any success body is accepted: the delete already happened, so a body
        // this SDK does not model must not turn it into an error.
        self.send::<serde::de::IgnoredAny>(
            HttpMethod::Delete,
            &product_path(product_id),
            profile_id,
            None,
            &[],
        )
        .await
        .map(|_| ())
    }

    /// Delete an archived product, then carry out the chosen action at each
    /// connected account it is tied to. `POST /products/{product_id}/delete`
    ///
    /// An account not named in `provider_actions` is kept as it is. A failed
    /// provider action does not undo the delete: it is listed by
    /// [`provider_cleanups`](Self::provider_cleanups) and retried with
    /// [`provider_archive`](Self::provider_archive).
    pub async fn delete_with_providers(
        &self,
        product_id: &str,
        profile_id: &str,
        params: &ProductDeleteRequest,
    ) -> Result<ProductDeleteResponse> {
        let path = format!("{}/delete", product_path(product_id));
        self.send_json(HttpMethod::Post, &path, profile_id, params)
            .await
    }

    /// Add a price to an existing product.
    /// `POST /products/{product_id}/prices`
    ///
    /// This is how a price changes: the new figure is added and the old price
    /// is archived, so both remain readable.
    pub async fn add_price(
        &self,
        product_id: &str,
        profile_id: &str,
        params: &ProductPriceCreateRequest,
    ) -> Result<ProductResponse> {
        let path = format!("{}/prices", product_path(product_id));
        self.send_json(HttpMethod::Post, &path, profile_id, params)
            .await
    }

    /// Change a price's label, its default flag or its metadata.
    /// `POST /products/{product_id}/prices/{price_id}`
    ///
    /// Not its amount, its currency or its interval.
    pub async fn update_price(
        &self,
        product_id: &str,
        price_id: &str,
        profile_id: &str,
        params: &ProductPriceUpdateRequest,
    ) -> Result<ProductResponse> {
        self.send_json(
            HttpMethod::Post,
            &price_path(product_id, price_id),
            profile_id,
            params,
        )
        .await
    }

    /// Take one price off sale, leaving the product on it.
    /// `POST /products/{product_id}/prices/{price_id}/archive`
    pub async fn archive_price(
        &self,
        product_id: &str,
        price_id: &str,
        profile_id: &str,
    ) -> Result<ProductResponse> {
        let path = format!("{}/archive", price_path(product_id, price_id));
        self.send(HttpMethod::Post, &path, profile_id, None, &[])
            .await
    }

    /// Add a group of optional extras to a one-time product, with how many
    /// of them a buyer must and may choose.
    /// `POST /products/{product_id}/addon-groups`
    ///
    /// Each add-on is an active product of kind `addon` in the same shop.
    pub async fn create_addon_group(
        &self,
        product_id: &str,
        profile_id: &str,
        params: &AddonGroupCreateRequest,
    ) -> Result<ProductResponse> {
        let path = format!("{}/addon-groups", product_path(product_id));
        self.send_json(HttpMethod::Post, &path, profile_id, params)
            .await
    }

    /// Change a group's name, bounds, or the add-ons it offers; a new list
    /// replaces the old one whole.
    /// `POST /products/{product_id}/addon-groups/{group_id}`
    pub async fn update_addon_group(
        &self,
        product_id: &str,
        group_id: &str,
        profile_id: &str,
        params: &AddonGroupUpdateRequest,
    ) -> Result<ProductResponse> {
        self.send_json(
            HttpMethod::Post,
            &addon_group_path(product_id, group_id),
            profile_id,
            params,
        )
        .await
    }

    /// Remove a group and what it offered. The add-on products themselves
    /// stay. `DELETE /products/{product_id}/addon-groups/{group_id}`
    pub async fn delete_addon_group(
        &self,
        product_id: &str,
        group_id: &str,
        profile_id: &str,
    ) -> Result<ProductResponse> {
        self.send(
            HttpMethod::Delete,
            &addon_group_path(product_id, group_id),
            profile_id,
            None,
            &[],
        )
        .await
    }

    /// Replace what a bundle contains. `POST /products/{product_id}/bundle`
    ///
    /// Its pricing mode is fixed at creation; past purchases keep their own
    /// frozen lines.
    pub async fn replace_bundle(
        &self,
        product_id: &str,
        profile_id: &str,
        params: &BundleDefinition,
    ) -> Result<ProductResponse> {
        let path = format!("{}/bundle", product_path(product_id));
        self.send_json(HttpMethod::Post, &path, profile_id, params)
            .await
    }

    /// Add a name the product goes by.
    /// `POST /products/{product_id}/aliases`
    ///
    /// A name it already goes by is returned as it is; one another product of
    /// the shop goes by is refused.
    pub async fn add_alias(
        &self,
        product_id: &str,
        profile_id: &str,
        params: &ProductAliasCreateRequest,
    ) -> Result<ProductResponse> {
        let path = format!("{}/aliases", product_path(product_id));
        self.send_json(HttpMethod::Post, &path, profile_id, params)
            .await
    }

    /// Remove a name the product goes by. Its current name stays.
    /// `POST /products/{product_id}/aliases/{alias_id}/remove`
    pub async fn remove_alias(
        &self,
        product_id: &str,
        alias_id: &str,
        profile_id: &str,
    ) -> Result<ProductResponse> {
        let path = format!(
            "{}/aliases/{}/remove",
            product_path(product_id),
            encode_segment(alias_id)
        );
        self.send(HttpMethod::Post, &path, profile_id, None, &[])
            .await
    }

    /// Tie a connected account's product, or one of its prices, to the
    /// product. `POST /products/{product_id}/connector-references`
    ///
    /// Recorded as `manual_id`: the ids are not checked against the account.
    pub async fn add_connector_reference(
        &self,
        product_id: &str,
        profile_id: &str,
        params: &ProductConnectorReferenceCreateRequest,
    ) -> Result<ProductResponse> {
        let path = format!("{}/connector-references", product_path(product_id));
        self.send_json(HttpMethod::Post, &path, profile_id, params)
            .await
    }

    /// Remove a connected account's product or price from the product.
    /// `POST /products/{product_id}/connector-references/{reference_id}/remove`
    pub async fn remove_connector_reference(
        &self,
        product_id: &str,
        reference_id: &str,
        profile_id: &str,
    ) -> Result<ProductResponse> {
        let path = format!(
            "{}/connector-references/{}/remove",
            product_path(product_id),
            encode_segment(reference_id)
        );
        self.send(HttpMethod::Post, &path, profile_id, None, &[])
            .await
    }

    /// One bounded page of a connected billing account's products, to pick
    /// an existing one to tie to a product. Reads only.
    /// `GET /products/import-suggestions`
    pub async fn import_suggestions(
        &self,
        profile_id: &str,
        params: &ProductImportSuggestionsParams,
    ) -> Result<Vec<SubscriptionItem>> {
        self.send(
            HttpMethod::Get,
            "/products/import-suggestions",
            profile_id,
            None,
            &params.to_query(),
        )
        .await
    }

    /// Tie one of a connected account's existing products (or a price of it)
    /// to the product, verified against a fresh read of the page it was
    /// suggested on — pass the same `limit` and `offset`. Recorded as
    /// `map_existing`.
    /// `POST /products/{product_id}/connector-references/import`
    pub async fn accept_import(
        &self,
        product_id: &str,
        profile_id: &str,
        params: &ProductImportAcceptRequest,
    ) -> Result<ProductResponse> {
        let path = format!("{}/connector-references/import", product_path(product_id));
        self.send_json(HttpMethod::Post, &path, profile_id, params)
            .await
    }

    /// Add a category to the shop, at the end of its order.
    /// `POST /products/categories`
    ///
    /// File products under it with `category_id` on create or update.
    pub async fn create_category(
        &self,
        profile_id: &str,
        params: &ProductCategoryCreateRequest,
    ) -> Result<ProductCategoryResponse> {
        self.send_json(HttpMethod::Post, "/products/categories", profile_id, params)
            .await
    }

    /// The shop's categories in order. Archived ones only with
    /// `include_archived`; deleted ones never.
    /// `GET /products/categories/list`
    pub async fn list_categories(
        &self,
        profile_id: &str,
        params: &ProductCategoryListParams,
    ) -> Result<ProductCategoryListResponse> {
        self.send(
            HttpMethod::Get,
            "/products/categories/list",
            profile_id,
            None,
            &params.to_query(),
        )
        .await
    }

    /// Put the shop's categories in a new order, and get them back in it.
    /// `POST /products/categories/reorder`
    ///
    /// Name every live category, archived ones included, exactly once.
    pub async fn reorder_categories(
        &self,
        profile_id: &str,
        params: &ProductCategoryReorderRequest,
    ) -> Result<ProductCategoryListResponse> {
        self.send_json(
            HttpMethod::Post,
            "/products/categories/reorder",
            profile_id,
            params,
        )
        .await
    }

    /// Rename a category. `POST /products/categories/{category_id}`
    pub async fn update_category(
        &self,
        category_id: &str,
        profile_id: &str,
        params: &ProductCategoryUpdateRequest,
    ) -> Result<ProductCategoryResponse> {
        self.send_json(
            HttpMethod::Post,
            &category_path(category_id),
            profile_id,
            params,
        )
        .await
    }

    /// Mark a category deleted, and get it back.
    /// `DELETE /products/categories/{category_id}`
    ///
    /// Its products become uncategorized and no payment changes.
    pub async fn delete_category(
        &self,
        category_id: &str,
        profile_id: &str,
    ) -> Result<ProductCategoryResponse> {
        self.send(
            HttpMethod::Delete,
            &category_path(category_id),
            profile_id,
            None,
            &[],
        )
        .await
    }

    /// Keep a category with its products, but file no new product under it.
    /// `POST /products/categories/{category_id}/archive`
    pub async fn archive_category(
        &self,
        category_id: &str,
        profile_id: &str,
    ) -> Result<ProductCategoryResponse> {
        let path = format!("{}/archive", category_path(category_id));
        self.send(HttpMethod::Post, &path, profile_id, None, &[])
            .await
    }

    /// Let an archived category take products again.
    /// `POST /products/categories/{category_id}/restore`
    pub async fn restore_category(
        &self,
        category_id: &str,
        profile_id: &str,
    ) -> Result<ProductCategoryResponse> {
        let path = format!("{}/restore", category_path(category_id));
        self.send(HttpMethod::Post, &path, profile_id, None, &[])
            .await
    }

    /// Read a connected billing account's products and say how each relates
    /// to the catalogue. `POST /products/import/preview`
    ///
    /// Reads only: nothing is written to the provider or the catalogue.
    pub async fn import_preview(
        &self,
        profile_id: &str,
        params: &ProductImportPreviewRequest,
    ) -> Result<ProductImportPreviewResponse> {
        self.send_json(
            HttpMethod::Post,
            "/products/import/preview",
            profile_id,
            params,
        )
        .await
    }

    /// Create a product for every new item and add the new prices of every
    /// changed one, tied to the provider's ids. `POST /products/import/apply`
    ///
    /// Nothing else is edited or removed, except that
    /// [`ProductImportArchivedAtProvider::Archive`] archives the catalogue
    /// product of every item the provider no longer offers. Nothing is
    /// written to the provider. A failed item is reported with its reason and
    /// can be retried by naming it in `connector_product_ids`.
    pub async fn import_apply(
        &self,
        profile_id: &str,
        params: &ProductImportApplyRequest,
    ) -> Result<ProductImportRunResponse> {
        self.send_json(
            HttpMethod::Post,
            "/products/import/apply",
            profile_id,
            params,
        )
        .await
    }

    /// The shop's past imports from one connected account, newest first.
    /// `GET /products/import/runs`
    pub async fn list_import_runs(
        &self,
        profile_id: &str,
        merchant_connector_id: &str,
    ) -> Result<ProductImportRunListResponse> {
        self.send(
            HttpMethod::Get,
            "/products/import/runs",
            profile_id,
            None,
            &[("merchant_connector_id", merchant_connector_id.to_string())],
        )
        .await
    }

    /// Compare the product with its copy at every connected account it is
    /// tied to. `GET /products/{product_id}/provider-sync`
    ///
    /// Reads the providers now; an unreadable provider answers `unknown`,
    /// never `in_sync`.
    pub async fn provider_sync(
        &self,
        product_id: &str,
        profile_id: &str,
    ) -> Result<ProductProviderSyncResponse> {
        let path = format!("{}/provider-sync", product_path(product_id));
        self.send(HttpMethod::Get, &path, profile_id, None, &[])
            .await
    }

    /// [`provider_sync`](Self::provider_sync) for 1 to 50 products at once,
    /// such as one page of the product list. Unknown ids are left out of the
    /// answer. `POST /products/provider-sync`
    pub async fn provider_sync_batch(
        &self,
        profile_id: &str,
        params: &ProductProviderSyncBatchRequest,
    ) -> Result<ProductProviderSyncBatchResponse> {
        self.send_json(
            HttpMethod::Post,
            "/products/provider-sync",
            profile_id,
            params,
        )
        .await
    }

    /// Write the catalogue's state onto one connected account's copy of the
    /// product, for the differences a push changes and nothing else.
    /// `POST /products/{product_id}/provider-sync/push`
    ///
    /// When it would change a difference not named in `confirmed`, nothing is
    /// written and the answer carries `confirmation_outdated: true` with the
    /// current differences in `result`; `nothing_to_push` answers without a
    /// provider write when nothing pushable differs.
    pub async fn provider_push(
        &self,
        product_id: &str,
        profile_id: &str,
        params: &ProductProviderPushRequest,
    ) -> Result<ProductProviderPushResponse> {
        let path = format!("{}/provider-sync/push", product_path(product_id));
        self.send_json(HttpMethod::Post, &path, profile_id, params)
            .await
    }

    /// The shop's connected accounts the catalogue works with, and what each
    /// can do. `GET /products/provider-accounts`
    pub async fn provider_accounts(&self, profile_id: &str) -> Result<ProviderAccountListResponse> {
        self.send(
            HttpMethod::Get,
            "/products/provider-accounts",
            profile_id,
            None,
            &[],
        )
        .await
    }

    /// Provider clean-ups still to be carried out: deletes whose action at a
    /// provider failed, or was recorded and never reached.
    /// `GET /products/provider-cleanups`
    pub async fn provider_cleanups(&self, profile_id: &str) -> Result<ProviderCleanupListResponse> {
        self.send(
            HttpMethod::Get,
            "/products/provider-cleanups",
            profile_id,
            None,
            &[],
        )
        .await
    }

    /// Create the product at a connected account it is not at yet.
    /// `POST /products/{product_id}/provider-sync/create`
    ///
    /// Without `confirmed` nothing is written and the answer holds the plan to
    /// review; send the plan's `fingerprint` back as `confirmed` to carry it
    /// out. When the plan changed since, nothing is written and the answer
    /// carries `confirmation_outdated: true` with the current plan.
    pub async fn provider_create(
        &self,
        product_id: &str,
        profile_id: &str,
        params: &ProductProviderCreateRequest,
    ) -> Result<ProductProviderCreateResponse> {
        let path = format!("{}/provider-sync/create", product_path(product_id));
        self.send_json(HttpMethod::Post, &path, profile_id, params)
            .await
    }

    /// Archive the product at one connected account, or retry a clean-up
    /// that failed after the product was deleted.
    /// `POST /products/{product_id}/provider-archive`
    ///
    /// Existing subscriptions there keep billing; the catalogue is not
    /// changed.
    pub async fn provider_archive(
        &self,
        product_id: &str,
        profile_id: &str,
        params: &ProviderArchiveRequest,
    ) -> Result<ProviderArchiveOutcome> {
        let path = format!("{}/provider-archive", product_path(product_id));
        self.send_json(HttpMethod::Post, &path, profile_id, params)
            .await
    }
}

/// `/products/{product_id}`, percent-encoded.
fn product_path(product_id: &str) -> String {
    format!("/products/{}", encode_segment(product_id))
}

/// `/products/{product_id}/prices/{price_id}`, both segments percent-encoded.
fn price_path(product_id: &str, price_id: &str) -> String {
    format!(
        "{}/prices/{}",
        product_path(product_id),
        encode_segment(price_id)
    )
}

/// `/products/{product_id}/addon-groups/{group_id}`, both segments
/// percent-encoded.
fn addon_group_path(product_id: &str, group_id: &str) -> String {
    format!(
        "{}/addon-groups/{}",
        product_path(product_id),
        encode_segment(group_id)
    )
}

/// `/products/categories/{category_id}`, percent-encoded.
fn category_path(category_id: &str) -> String {
    format!("/products/categories/{}", encode_segment(category_id))
}

/// A price to create with a product, or to add to one.
#[derive(Debug, Clone, Serialize)]
pub struct ProductPriceCreateRequest {
    /// The price's label.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub nickname: Option<String>,
    /// Minor units, in `currency`.
    pub amount: i64,
    /// Three-letter ISO 4217 currency code.
    pub currency: Currency,
    /// The unit a recurring price bills in. Set together with
    /// `billing_interval_count`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub billing_interval: Option<ProductPriceInterval>,
    /// How many `billing_interval`s one billing period lasts.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub billing_interval_count: Option<i32>,
    /// The trial's length, in `trial_period_unit`s.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trial_period: Option<i32>,
    /// The unit the trial is measured in.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trial_period_unit: Option<ProductPriceInterval>,
    /// The price a checkout picks when none is named.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub is_default: Option<bool>,
    /// Whether the amount includes tax (the default) or has it added on top.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tax_behavior: Option<ProductPriceTaxBehavior>,
    /// Your own key-value data.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Value>,
}

impl ProductPriceCreateRequest {
    /// A one-time price of `amount` minor units in `currency`.
    pub fn new(amount: i64, currency: impl Into<Currency>) -> Self {
        Self {
            nickname: None,
            amount,
            currency: currency.into(),
            billing_interval: None,
            billing_interval_count: None,
            trial_period: None,
            trial_period_unit: None,
            is_default: None,
            tax_behavior: None,
            metadata: None,
        }
    }

    /// Bill the price every `count` `interval`s, making it recurring.
    #[must_use]
    pub fn recurring(mut self, interval: ProductPriceInterval, count: i32) -> Self {
        self.billing_interval = Some(interval);
        self.billing_interval_count = Some(count);
        self
    }

    /// Start subscriptions on the price with a trial of `period` `unit`s.
    #[must_use]
    pub fn trial(mut self, period: i32, unit: ProductPriceInterval) -> Self {
        self.trial_period = Some(period);
        self.trial_period_unit = Some(unit);
        self
    }

    /// Set the price's label.
    #[must_use]
    pub fn nickname(mut self, nickname: impl Into<String>) -> Self {
        self.nickname = Some(nickname.into());
        self
    }

    /// Make the price the one a checkout picks when none is named.
    #[must_use]
    pub fn is_default(mut self, is_default: bool) -> Self {
        self.is_default = Some(is_default);
        self
    }

    /// Say whether the amount includes tax or has it added on top by the
    /// billing processor. `Exclusive` is refused unless the price is recurring,
    /// billed by Creem, and the deployment allows it. Fixed once the price
    /// exists.
    #[must_use]
    pub fn tax_behavior(mut self, tax_behavior: ProductPriceTaxBehavior) -> Self {
        self.tax_behavior = Some(tax_behavior);
        self
    }

    /// Set your own key-value data.
    #[must_use]
    pub fn metadata(mut self, metadata: Value) -> Self {
        self.metadata = Some(metadata);
        self
    }
}

/// Body of [`Products::create`]: a product with at least one price.
#[derive(Debug, Clone, Serialize)]
pub struct ProductCreateRequest {
    /// Your own id for the product: 1–64 ASCII letters, digits, `-` and `_`,
    /// unique across every shop of the merchant account and fixed once
    /// created. Absent, one is generated. It may not be one of the
    /// `/products` route segments `list`, `images`, `resolve`,
    /// `import-suggestions`, `import` or `categories`, in any letter case.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub product_id: Option<String>,
    /// The product's name.
    pub name: String,
    /// Other names the product goes by, such as a SKU; at most 20. No other
    /// product of the shop may go by one of them.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub aliases: Option<Vec<String>>,
    /// Free-form description.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// The product's image, e.g. from [`Products::upload_image`].
    #[serde(skip_serializing_if = "Option::is_none")]
    pub image_url: Option<String>,
    /// What the product is sold as.
    pub kind: ProductKind,
    /// The prices the product is sold at. At least one, except for a bundle
    /// priced as the sum of its components, which has none.
    pub prices: Vec<ProductPriceCreateRequest>,
    /// What a bundle contains and how it is priced. Required for a bundle,
    /// refused for every other kind.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub bundle: Option<BundleDefinition>,
    /// Your own key-value data.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Value>,
    /// The shop category to file the product under: an active category of
    /// the same shop. Uncategorized when absent.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub category_id: Option<String>,
    /// Let the buyer choose the product's add-ons in the hosted checkout.
    /// Only for a `one_time` product; `false` by default.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub buyer_chooses_addons: Option<bool>,
    /// The tax category the invoice tax rules match on, `[a-z0-9_]{1,32}`.
    /// Absent is `standard`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tax_category: Option<String>,
}

impl ProductCreateRequest {
    /// A product named `name`, of `kind`, sold at `prices`.
    pub fn new(
        name: impl Into<String>,
        kind: ProductKind,
        prices: Vec<ProductPriceCreateRequest>,
    ) -> Self {
        Self {
            product_id: None,
            name: name.into(),
            aliases: None,
            description: None,
            image_url: None,
            kind,
            prices,
            bundle: None,
            metadata: None,
            category_id: None,
            buyer_chooses_addons: None,
            tax_category: None,
        }
    }

    /// Choose the product's id.
    #[must_use]
    pub fn product_id(mut self, product_id: impl Into<String>) -> Self {
        self.product_id = Some(product_id.into());
        self
    }

    /// Set the other names the product goes by.
    #[must_use]
    pub fn aliases(mut self, aliases: Vec<String>) -> Self {
        self.aliases = Some(aliases);
        self
    }

    /// Set the product's description.
    #[must_use]
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// Set the product's image.
    #[must_use]
    pub fn image_url(mut self, image_url: impl Into<String>) -> Self {
        self.image_url = Some(image_url.into());
        self
    }

    /// Set what a bundle contains and how it is priced.
    #[must_use]
    pub fn bundle(mut self, bundle: BundleDefinition) -> Self {
        self.bundle = Some(bundle);
        self
    }

    /// Set your own key-value data.
    #[must_use]
    pub fn metadata(mut self, metadata: Value) -> Self {
        self.metadata = Some(metadata);
        self
    }

    /// File the product under a category.
    #[must_use]
    pub fn category_id(mut self, category_id: impl Into<String>) -> Self {
        self.category_id = Some(category_id.into());
        self
    }

    /// Let the buyer choose the add-ons in the hosted checkout.
    #[must_use]
    pub fn buyer_chooses_addons(mut self, buyer_chooses_addons: bool) -> Self {
        self.buyer_chooses_addons = Some(buyer_chooses_addons);
        self
    }

    /// Set the tax category.
    #[must_use]
    pub fn tax_category(mut self, tax_category: impl Into<String>) -> Self {
        self.tax_category = Some(tax_category.into());
        self
    }
}

/// Body of [`Products::update`]. Only the fields you set are sent.
#[derive(Debug, Clone, Default, Serialize)]
pub struct ProductUpdateRequest {
    /// A new name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// A new description.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// A new image.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub image_url: Option<String>,
    /// New key-value data.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Value>,
    /// `Some(Some(id))` moves the product to another active category of the
    /// shop, `Some(None)` sends `null` and makes it uncategorized, `None`
    /// leaves it where it is. Payment lines keep what they froze.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub category_id: Option<Option<String>>,
    /// Let the buyer choose the add-ons in the hosted checkout. Only a
    /// `one_time` product can. Applies to payments created afterwards.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub buyer_chooses_addons: Option<bool>,
    /// `Some(Some(category))` sets a new tax category (`[a-z0-9_]{1,32}`),
    /// `Some(None)` sends `null` for `standard`, `None` leaves it. Invoices
    /// already drafted keep the category they were created with.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tax_category: Option<Option<String>>,
}

impl ProductUpdateRequest {
    /// An empty update; set the fields you want changed.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the product's name.
    #[must_use]
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Set the product's description.
    #[must_use]
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// Set the product's image.
    #[must_use]
    pub fn image_url(mut self, image_url: impl Into<String>) -> Self {
        self.image_url = Some(image_url.into());
        self
    }

    /// Set your own key-value data.
    #[must_use]
    pub fn metadata(mut self, metadata: Value) -> Self {
        self.metadata = Some(metadata);
        self
    }

    /// Move the product to a category.
    #[must_use]
    pub fn category_id(mut self, category_id: impl Into<String>) -> Self {
        self.category_id = Some(Some(category_id.into()));
        self
    }

    /// Make the product uncategorized.
    #[must_use]
    pub fn uncategorized(mut self) -> Self {
        self.category_id = Some(None);
        self
    }

    /// Let the buyer choose the add-ons in the hosted checkout, or not.
    #[must_use]
    pub fn buyer_chooses_addons(mut self, buyer_chooses_addons: bool) -> Self {
        self.buyer_chooses_addons = Some(buyer_chooses_addons);
        self
    }

    /// Set the tax category.
    #[must_use]
    pub fn tax_category(mut self, tax_category: impl Into<String>) -> Self {
        self.tax_category = Some(Some(tax_category.into()));
        self
    }

    /// Put the product back on the `standard` tax category.
    #[must_use]
    pub fn standard_tax_category(mut self) -> Self {
        self.tax_category = Some(None);
        self
    }
}

/// Body of [`Products::update_price`]: its label, its default flag, its
/// metadata. Only the fields you set are sent.
#[derive(Debug, Clone, Default, Serialize)]
pub struct ProductPriceUpdateRequest {
    /// A new label.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub nickname: Option<String>,
    /// Make the price the default, or not.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub is_default: Option<bool>,
    /// New key-value data.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Value>,
}

impl ProductPriceUpdateRequest {
    /// An empty update; set the fields you want changed.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the price's label.
    #[must_use]
    pub fn nickname(mut self, nickname: impl Into<String>) -> Self {
        self.nickname = Some(nickname.into());
        self
    }

    /// Make the price the default, or not.
    #[must_use]
    pub fn is_default(mut self, is_default: bool) -> Self {
        self.is_default = Some(is_default);
        self
    }

    /// Set your own key-value data.
    #[must_use]
    pub fn metadata(mut self, metadata: Value) -> Self {
        self.metadata = Some(metadata);
        self
    }
}

/// Body of [`Products::create_addon_group`].
///
/// `min_choices` of 0 makes the group optional, and it cannot exceed the
/// number of add-ons the group offers. An add-on is offered by at most one
/// group of the same product.
#[derive(Debug, Clone, Serialize)]
pub struct AddonGroupCreateRequest {
    /// The group's name.
    pub name: String,
    /// How many add-ons a buyer must choose.
    pub min_choices: i32,
    /// How many add-ons a buyer may choose.
    pub max_choices: i32,
    /// The add-on products the group offers, in order: active products of
    /// kind `addon` in the same shop.
    pub addon_product_ids: Vec<String>,
}

impl AddonGroupCreateRequest {
    /// A group named `name` offering `addon_product_ids`, of which a buyer
    /// chooses `min_choices` to `max_choices`.
    pub fn new(
        name: impl Into<String>,
        min_choices: i32,
        max_choices: i32,
        addon_product_ids: Vec<String>,
    ) -> Self {
        Self {
            name: name.into(),
            min_choices,
            max_choices,
            addon_product_ids,
        }
    }
}

/// Body of [`Products::update_addon_group`]. Only the fields you set are
/// sent; `addon_product_ids` replaces the whole list.
#[derive(Debug, Clone, Default, Serialize)]
pub struct AddonGroupUpdateRequest {
    /// A new name.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// A new lower bound.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_choices: Option<i32>,
    /// A new upper bound.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_choices: Option<i32>,
    /// The add-ons the group offers from now on, in order.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub addon_product_ids: Option<Vec<String>>,
}

impl AddonGroupUpdateRequest {
    /// An empty update; set the fields you want changed.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the group's name.
    #[must_use]
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Set how many add-ons a buyer must and may choose.
    #[must_use]
    pub fn choices(mut self, min_choices: i32, max_choices: i32) -> Self {
        self.min_choices = Some(min_choices);
        self.max_choices = Some(max_choices);
        self
    }

    /// Replace the add-ons the group offers.
    #[must_use]
    pub fn addon_product_ids(mut self, addon_product_ids: Vec<String>) -> Self {
        self.addon_product_ids = Some(addon_product_ids);
        self
    }
}

/// One component of a bundle.
#[derive(Debug, Clone, Serialize)]
pub struct BundleItemRequest {
    /// The component: an active one-time product of the same shop, never
    /// another bundle.
    pub product_id: String,
    /// How many of it the bundle holds; 1 by default.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub quantity: Option<i32>,
}

impl BundleItemRequest {
    /// One unit of `product_id`.
    pub fn new(product_id: impl Into<String>) -> Self {
        Self {
            product_id: product_id.into(),
            quantity: None,
        }
    }

    /// Hold `quantity` units of the component.
    #[must_use]
    pub fn quantity(mut self, quantity: i32) -> Self {
        self.quantity = Some(quantity);
        self
    }
}

/// What a bundle contains and how it is priced. Under
/// [`BundlePricing::Sum`] every component's default price has to be in one
/// currency.
#[derive(Debug, Clone, Serialize)]
pub struct BundleDefinition {
    /// How the bundle is priced.
    pub pricing: BundlePricing,
    /// The components, in order.
    pub items: Vec<BundleItemRequest>,
}

impl BundleDefinition {
    /// A bundle of `items`, priced by `pricing`.
    pub fn new(pricing: BundlePricing, items: Vec<BundleItemRequest>) -> Self {
        Self { pricing, items }
    }
}

/// Body of [`Products::add_alias`].
#[derive(Debug, Clone, Serialize)]
pub struct ProductAliasCreateRequest {
    /// The name. No other product of the shop may go by it; ASCII letter case
    /// and repeated whitespace do not tell two names apart.
    pub alias: String,
}

impl ProductAliasCreateRequest {
    /// A request adding the name `alias`.
    pub fn new(alias: impl Into<String>) -> Self {
        Self {
            alias: alias.into(),
        }
    }
}

/// Body of [`Products::add_connector_reference`]. The ids are stored as given
/// and are not checked against the connected account.
#[derive(Debug, Clone, Serialize)]
pub struct ProductConnectorReferenceCreateRequest {
    /// The connected account the ids belong to; one of the shop's.
    pub merchant_connector_id: String,
    /// The connector's id for the product. No other product of the shop may
    /// hold it for the same connector.
    pub connector_product_id: String,
    /// The connector's id for one of that product's prices. The reference to
    /// the connector's product is added with it when this product does not
    /// hold it yet.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub connector_price_id: Option<String>,
    /// The price of this product the connector's price stands for. Only
    /// together with `connector_price_id`, and only an active price.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub price_id: Option<String>,
    /// What the connector calls the product or the price.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub display_name: Option<String>,
}

impl ProductConnectorReferenceCreateRequest {
    /// A reference to `connector_product_id` at `merchant_connector_id`.
    pub fn new(
        merchant_connector_id: impl Into<String>,
        connector_product_id: impl Into<String>,
    ) -> Self {
        Self {
            merchant_connector_id: merchant_connector_id.into(),
            connector_product_id: connector_product_id.into(),
            connector_price_id: None,
            price_id: None,
            display_name: None,
        }
    }

    /// Reference one of the connector product's prices, standing for
    /// `price_id` of this product.
    #[must_use]
    pub fn price(
        mut self,
        connector_price_id: impl Into<String>,
        price_id: impl Into<String>,
    ) -> Self {
        self.connector_price_id = Some(connector_price_id.into());
        self.price_id = Some(price_id.into());
        self
    }

    /// Reference one of the connector product's prices, standing for none of
    /// this product's prices.
    #[must_use]
    pub fn connector_price_id(mut self, connector_price_id: impl Into<String>) -> Self {
        self.connector_price_id = Some(connector_price_id.into());
        self
    }

    /// Set what the connector calls the product or the price.
    #[must_use]
    pub fn display_name(mut self, display_name: impl Into<String>) -> Self {
        self.display_name = Some(display_name.into());
        self
    }
}

/// Query of [`Products::import_suggestions`]: one bounded page of a
/// connected billing account's products.
#[derive(Debug, Clone)]
pub struct ProductImportSuggestionsParams {
    /// The connected billing account.
    pub merchant_connector_id: String,
    /// Page size, 1 to 20 (20 by default).
    pub limit: Option<u32>,
    /// The connector's pagination offset (0 by default).
    pub offset: Option<u32>,
}

impl ProductImportSuggestionsParams {
    /// The first page of `merchant_connector_id`'s products.
    pub fn new(merchant_connector_id: impl Into<String>) -> Self {
        Self {
            merchant_connector_id: merchant_connector_id.into(),
            limit: None,
            offset: None,
        }
    }

    /// Set the page size.
    #[must_use]
    pub fn limit(mut self, limit: u32) -> Self {
        self.limit = Some(limit);
        self
    }

    /// Set the pagination offset.
    #[must_use]
    pub fn offset(mut self, offset: u32) -> Self {
        self.offset = Some(offset);
        self
    }

    fn to_query(&self) -> Vec<(&'static str, String)> {
        let mut q = vec![("merchant_connector_id", self.merchant_connector_id.clone())];
        if let Some(v) = self.limit {
            q.push(("limit", v.to_string()));
        }
        if let Some(v) = self.offset {
            q.push(("offset", v.to_string()));
        }
        q
    }
}

/// Body of [`Products::accept_import`]: one of a connected account's existing
/// products, verified against a fresh read of the page it was suggested on.
#[derive(Debug, Clone, Serialize)]
pub struct ProductImportAcceptRequest {
    /// The connected account.
    pub merchant_connector_id: String,
    /// The connector's id for the product.
    pub connector_product_id: String,
    /// The connector's id for one of the product's prices.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub connector_price_id: Option<String>,
    /// The price of this product the connector's price stands for.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub price_id: Option<String>,
    /// The page size the suggestion was obtained with.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
    /// The offset the suggestion was obtained with.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub offset: Option<u32>,
}

impl ProductImportAcceptRequest {
    /// Accept `connector_product_id` at `merchant_connector_id`.
    pub fn new(
        merchant_connector_id: impl Into<String>,
        connector_product_id: impl Into<String>,
    ) -> Self {
        Self {
            merchant_connector_id: merchant_connector_id.into(),
            connector_product_id: connector_product_id.into(),
            connector_price_id: None,
            price_id: None,
            limit: None,
            offset: None,
        }
    }

    /// Accept one of the connector product's prices, standing for
    /// `price_id` of this product.
    #[must_use]
    pub fn price(
        mut self,
        connector_price_id: impl Into<String>,
        price_id: impl Into<String>,
    ) -> Self {
        self.connector_price_id = Some(connector_price_id.into());
        self.price_id = Some(price_id.into());
        self
    }

    /// The page the suggestion was read from.
    #[must_use]
    pub fn page(mut self, limit: u32, offset: u32) -> Self {
        self.limit = Some(limit);
        self.offset = Some(offset);
        self
    }
}

/// Body of [`Products::create_category`].
#[derive(Debug, Clone, Serialize)]
pub struct ProductCategoryCreateRequest {
    /// The category's name, at most 255 characters; leading and trailing
    /// whitespace is removed. No other live category of the shop may have
    /// the same name, ignoring case.
    pub name: String,
}

impl ProductCategoryCreateRequest {
    /// A category named `name`.
    pub fn new(name: impl Into<String>) -> Self {
        Self { name: name.into() }
    }
}

/// Body of [`Products::update_category`]. Only the fields you set are sent.
#[derive(Debug, Clone, Default, Serialize)]
pub struct ProductCategoryUpdateRequest {
    /// A new name, under the same rules as on create.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
}

impl ProductCategoryUpdateRequest {
    /// An empty update; set the fields you want changed.
    pub fn new() -> Self {
        Self::default()
    }

    /// Rename the category.
    #[must_use]
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }
}

/// Body of [`Products::reorder_categories`].
#[derive(Debug, Clone, Serialize)]
pub struct ProductCategoryReorderRequest {
    /// Every live category of the shop, archived ones included, each exactly
    /// once, in the order to show them.
    pub category_ids: Vec<String>,
}

impl ProductCategoryReorderRequest {
    /// The shop's categories in the order `category_ids`.
    pub fn new(category_ids: Vec<String>) -> Self {
        Self { category_ids }
    }
}

/// Query of [`Products::list_categories`].
#[derive(Debug, Clone, Default)]
pub struct ProductCategoryListParams {
    /// Include archived categories. Deleted categories are never listed.
    pub include_archived: Option<bool>,
}

impl ProductCategoryListParams {
    /// The shop's active categories.
    pub fn new() -> Self {
        Self::default()
    }

    /// Include archived categories, or not.
    #[must_use]
    pub fn include_archived(mut self, include_archived: bool) -> Self {
        self.include_archived = Some(include_archived);
        self
    }

    fn to_query(&self) -> Vec<(&'static str, String)> {
        let mut q = Vec::new();
        if let Some(v) = self.include_archived {
            q.push(("include_archived", v.to_string()));
        }
        q
    }
}

/// Query of [`Products::list`]. A `category_id` together with
/// `uncategorized: true` asks for two different things, and is refused.
#[derive(Debug, Clone, Default)]
pub struct ProductListParams {
    /// Only products in this status.
    pub status: Option<ProductStatus>,
    /// Only products filed under this category of the shop.
    pub category_id: Option<String>,
    /// `true`: only products under no category.
    pub uncategorized: Option<bool>,
    /// Page size, 1 to 100.
    pub limit: Option<u32>,
    /// How many products to skip.
    pub offset: Option<u32>,
}

impl ProductListParams {
    /// The first page of every product.
    pub fn new() -> Self {
        Self::default()
    }

    /// Only products in `status`.
    #[must_use]
    pub fn status(mut self, status: ProductStatus) -> Self {
        self.status = Some(status);
        self
    }

    /// Only products filed under `category_id`.
    #[must_use]
    pub fn category_id(mut self, category_id: impl Into<String>) -> Self {
        self.category_id = Some(category_id.into());
        self
    }

    /// Only products under no category.
    #[must_use]
    pub fn uncategorized(mut self) -> Self {
        self.uncategorized = Some(true);
        self
    }

    /// Set the page size.
    #[must_use]
    pub fn limit(mut self, limit: u32) -> Self {
        self.limit = Some(limit);
        self
    }

    /// Set how many products to skip.
    #[must_use]
    pub fn offset(mut self, offset: u32) -> Self {
        self.offset = Some(offset);
        self
    }

    fn to_query(&self) -> Vec<(&'static str, String)> {
        let mut q = Vec::new();
        if let Some(v) = self.status {
            q.push(("status", v.as_str().to_string()));
        }
        if let Some(v) = &self.category_id {
            q.push(("category_id", v.clone()));
        }
        if let Some(v) = self.uncategorized {
            q.push(("uncategorized", v.to_string()));
        }
        if let Some(v) = self.limit {
            q.push(("limit", v.to_string()));
        }
        if let Some(v) = self.offset {
            q.push(("offset", v.to_string()));
        }
        q
    }
}

/// What [`Products::resolve`] finds a product by. The API refuses every other
/// combination, so the type does too.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum ProductResolveQuery {
    /// Any name the product goes by, its current name included. ASCII letter
    /// case and repeated whitespace are ignored.
    Alias(String),
    /// A connector's id for a product.
    ConnectorProduct {
        /// The connector the id belongs to, such as `stripe`.
        connector: String,
        /// The connector's id for the product.
        connector_product_id: String,
    },
    /// A connector's id for a price.
    ConnectorPrice {
        /// The connector the id belongs to, such as `stripe`.
        connector: String,
        /// The connector's id for the price.
        connector_price_id: String,
    },
}

impl ProductResolveQuery {
    /// Resolve by a name the product goes by.
    pub fn alias(alias: impl Into<String>) -> Self {
        Self::Alias(alias.into())
    }

    /// Resolve by a connector's id for a product.
    pub fn connector_product(
        connector: impl Into<String>,
        connector_product_id: impl Into<String>,
    ) -> Self {
        Self::ConnectorProduct {
            connector: connector.into(),
            connector_product_id: connector_product_id.into(),
        }
    }

    /// Resolve by a connector's id for a price.
    pub fn connector_price(
        connector: impl Into<String>,
        connector_price_id: impl Into<String>,
    ) -> Self {
        Self::ConnectorPrice {
            connector: connector.into(),
            connector_price_id: connector_price_id.into(),
        }
    }

    fn to_query(&self) -> Vec<(&'static str, String)> {
        match self {
            Self::Alias(alias) => vec![("alias", alias.clone())],
            Self::ConnectorProduct {
                connector,
                connector_product_id,
            } => vec![
                ("connector", connector.clone()),
                ("connector_product_id", connector_product_id.clone()),
            ],
            Self::ConnectorPrice {
                connector,
                connector_price_id,
            } => vec![
                ("connector", connector.clone()),
                ("connector_price_id", connector_price_id.clone()),
            ],
        }
    }
}

/// Query of [`Products::sales`]: which sales of a product to total.
#[derive(Debug, Clone)]
pub struct ProductSalesParams {
    /// Payments created at or after this time (ISO 8601).
    pub start_time: String,
    /// Payments created at or before this time; absent means now.
    pub end_time: Option<String>,
    /// `true` totals test payments, `false` live ones — never both together.
    pub test_mode: bool,
}

impl ProductSalesParams {
    /// Sales since `start_time`, in test or live payments.
    pub fn new(start_time: impl Into<String>, test_mode: bool) -> Self {
        Self {
            start_time: start_time.into(),
            end_time: None,
            test_mode,
        }
    }

    /// End the window at `end_time`.
    #[must_use]
    pub fn end_time(mut self, end_time: impl Into<String>) -> Self {
        self.end_time = Some(end_time.into());
        self
    }

    fn to_query(&self) -> Vec<(&'static str, String)> {
        let mut q = vec![("start_time", self.start_time.clone())];
        if let Some(v) = &self.end_time {
            q.push(("end_time", v.clone()));
        }
        q.push(("test_mode", self.test_mode.to_string()));
        q
    }
}

/// What a catalogue import brings over.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ProductImportScope {
    /// Recurring products.
    ProductsRecurring,
    /// One-time products.
    ProductsOneTime,
}

/// What to do with a provider product sold both once and on a schedule.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ProductImportMixedDecision {
    /// Make two catalogue products, one per kind, where the deployment splits
    /// such products; elsewhere read as `recurring_only`.
    Split,
    /// Import one recurring product and leave the one-time prices out.
    RecurringOnly,
    /// Leave the item out.
    Skip,
}

/// What to do with a tied catalogue product the provider no longer offers.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ProductImportArchivedAtProvider {
    /// Leave the catalogue product as it is.
    Skip,
    /// Archive the catalogue product on apply.
    Archive,
}

/// Options of an import preview or apply.
#[derive(Debug, Clone, Default, Serialize)]
pub struct ProductImportOptions {
    /// What to do with a product sold both ways; `split` by default.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mixed: Option<ProductImportMixedDecision>,
    /// What an apply does with a tied product the provider no longer offers;
    /// `skip` by default.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub archived: Option<ProductImportArchivedAtProvider>,
}

impl ProductImportOptions {
    /// The default options.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set what to do with a product sold both ways.
    #[must_use]
    pub fn mixed(mut self, mixed: ProductImportMixedDecision) -> Self {
        self.mixed = Some(mixed);
        self
    }

    /// Set what an apply does with a product the provider no longer offers.
    #[must_use]
    pub fn archived(mut self, archived: ProductImportArchivedAtProvider) -> Self {
        self.archived = Some(archived);
        self
    }
}

/// Body of [`Products::import_preview`].
#[derive(Debug, Clone, Serialize)]
pub struct ProductImportPreviewRequest {
    /// The connected billing account to read.
    pub merchant_connector_id: String,
    /// What to import; both kinds when absent.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub scopes: Option<Vec<ProductImportScope>>,
    /// Import options.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub options: Option<ProductImportOptions>,
}

impl ProductImportPreviewRequest {
    /// A preview of everything at `merchant_connector_id`.
    pub fn new(merchant_connector_id: impl Into<String>) -> Self {
        Self {
            merchant_connector_id: merchant_connector_id.into(),
            scopes: None,
            options: None,
        }
    }

    /// Narrow what is read.
    #[must_use]
    pub fn scopes(mut self, scopes: Vec<ProductImportScope>) -> Self {
        self.scopes = Some(scopes);
        self
    }

    /// Set the import options.
    #[must_use]
    pub fn options(mut self, options: ProductImportOptions) -> Self {
        self.options = Some(options);
        self
    }
}

/// Body of [`Products::import_apply`].
///
/// `new` and `changed` items are imported; an `unavailable` item's catalogue
/// product is archived only when the options ask for it. Nothing else does
/// anything.
#[derive(Debug, Clone, Serialize)]
pub struct ProductImportApplyRequest {
    /// The connected billing account to import from.
    pub merchant_connector_id: String,
    /// Narrow the apply to these items, e.g. to retry the ones a previous run
    /// reported as failed.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub connector_product_ids: Option<Vec<String>>,
    /// The `confirmation` of the preview reviewed. When the provider's
    /// listing or the catalogue's ties moved since, nothing is written and the
    /// run comes back `outdated` with `confirmation_outdated: true`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub confirmation: Option<String>,
    /// Per provider product sold both ways, keyed by its
    /// `connector_product_id`. Overrides the options' `mixed`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub decisions: Option<BTreeMap<String, ProductImportMixedDecision>>,
    /// What to import; both kinds when absent.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub scopes: Option<Vec<ProductImportScope>>,
    /// Import options.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub options: Option<ProductImportOptions>,
}

impl ProductImportApplyRequest {
    /// An apply of everything at `merchant_connector_id`.
    pub fn new(merchant_connector_id: impl Into<String>) -> Self {
        Self {
            merchant_connector_id: merchant_connector_id.into(),
            connector_product_ids: None,
            confirmation: None,
            decisions: None,
            scopes: None,
            options: None,
        }
    }

    /// Narrow the apply to these items.
    #[must_use]
    pub fn connector_product_ids(mut self, connector_product_ids: Vec<String>) -> Self {
        self.connector_product_ids = Some(connector_product_ids);
        self
    }

    /// Confirm the preview reviewed.
    #[must_use]
    pub fn confirmation(mut self, confirmation: impl Into<String>) -> Self {
        self.confirmation = Some(confirmation.into());
        self
    }

    /// Decide what to do with one product sold both ways.
    #[must_use]
    pub fn decision(
        mut self,
        connector_product_id: impl Into<String>,
        decision: ProductImportMixedDecision,
    ) -> Self {
        self.decisions
            .get_or_insert_with(BTreeMap::new)
            .insert(connector_product_id.into(), decision);
        self
    }

    /// Narrow what is imported.
    #[must_use]
    pub fn scopes(mut self, scopes: Vec<ProductImportScope>) -> Self {
        self.scopes = Some(scopes);
        self
    }

    /// Set the import options.
    #[must_use]
    pub fn options(mut self, options: ProductImportOptions) -> Self {
        self.options = Some(options);
        self
    }
}

/// Body of [`Products::provider_sync_batch`]: 1 to 50 product ids of the
/// shop.
#[derive(Debug, Clone, Serialize)]
pub struct ProductProviderSyncBatchRequest {
    /// The products to compare.
    pub product_ids: Vec<String>,
}

impl ProductProviderSyncBatchRequest {
    /// A comparison of `product_ids`.
    pub fn new(product_ids: Vec<String>) -> Self {
        Self { product_ids }
    }
}

/// Body of [`Products::provider_push`].
#[derive(Debug, Clone, Serialize)]
pub struct ProductProviderPushRequest {
    /// The connected account to write to.
    pub merchant_connector_id: String,
    /// The `key` of every difference reviewed, exactly as received.
    pub confirmed: Vec<String>,
}

impl ProductProviderPushRequest {
    /// A push to `merchant_connector_id` of the differences named in
    /// `confirmed`.
    pub fn new(merchant_connector_id: impl Into<String>, confirmed: Vec<String>) -> Self {
        Self {
            merchant_connector_id: merchant_connector_id.into(),
            confirmed,
        }
    }
}

/// Body of [`Products::provider_create`].
#[derive(Debug, Clone, Serialize)]
pub struct ProductProviderCreateRequest {
    /// The connected account to create the product at.
    pub merchant_connector_id: String,
    /// The catalogue prices to create; every active price the provider can
    /// hold when absent.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub price_ids: Option<Vec<String>>,
    /// The `fingerprint` of the plan reviewed. Absent, nothing is written and
    /// the answer holds the plan.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub confirmed: Option<String>,
}

impl ProductProviderCreateRequest {
    /// A plan for creating the product at `merchant_connector_id`.
    pub fn new(merchant_connector_id: impl Into<String>) -> Self {
        Self {
            merchant_connector_id: merchant_connector_id.into(),
            price_ids: None,
            confirmed: None,
        }
    }

    /// Create only these catalogue prices.
    #[must_use]
    pub fn price_ids(mut self, price_ids: Vec<String>) -> Self {
        self.price_ids = Some(price_ids);
        self
    }

    /// Carry out the plan with this `fingerprint`.
    #[must_use]
    pub fn confirmed(mut self, fingerprint: impl Into<String>) -> Self {
        self.confirmed = Some(fingerprint.into());
        self
    }
}

/// What to do at one connected account: the body of
/// [`Products::provider_archive`], and one entry of a
/// [`ProductDeleteRequest`].
#[derive(Debug, Clone, Serialize)]
pub struct ProviderArchiveRequest {
    /// The connected account.
    pub merchant_connector_id: String,
    /// What to do there.
    pub action: ProviderArchiveAction,
    /// On a retry: the provider object to act on, as a pending clean-up names
    /// it. Without it, one whose clean-up is pending is taken, else the
    /// first. A delete acts on every object at the account and ignores it.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub connector_product_id: Option<String>,
}

impl ProviderArchiveRequest {
    /// `action` at `merchant_connector_id`.
    pub fn new(merchant_connector_id: impl Into<String>, action: ProviderArchiveAction) -> Self {
        Self {
            merchant_connector_id: merchant_connector_id.into(),
            action,
            connector_product_id: None,
        }
    }

    /// Act on this provider object.
    #[must_use]
    pub fn connector_product_id(mut self, connector_product_id: impl Into<String>) -> Self {
        self.connector_product_id = Some(connector_product_id.into());
        self
    }
}

/// Body of [`Products::delete_with_providers`].
#[derive(Debug, Clone, Default, Serialize)]
pub struct ProductDeleteRequest {
    /// What to do at each connected account. An account the product is tied
    /// to and not named here is kept as it is.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub provider_actions: Vec<ProviderArchiveRequest>,
}

impl ProductDeleteRequest {
    /// A delete that keeps every connected account's copy.
    pub fn new() -> Self {
        Self::default()
    }

    /// Add what to do at one connected account.
    #[must_use]
    pub fn provider_action(mut self, action: ProviderArchiveRequest) -> Self {
        self.provider_actions.push(action);
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::models::product::{
        PriceBillingState, ProductAliasKind, ProductImportClassification, ProductMappingMode,
        ProductMatch, ProductPriceResponse, ProviderArchiveMode, ProviderArchiveStatus,
        ProviderPushAction, ProviderSyncField, ProviderSyncStatus,
    };
    use crate::http::mock::{Step, client_with, client_with_retries};
    use serde_json::json;

    const PRICE_JSON: &str = r#"{
        "id": "price_1",
        "product_id": "prd_1",
        "nickname": "Monthly",
        "amount": 1999,
        "currency": "EUR",
        "billing_interval": "month",
        "billing_interval_count": 1,
        "is_default": true,
        "status": "active",
        "created_at": "2026-01-01T00:00:00Z",
        "modified_at": "2026-01-01T00:00:00Z",
        "price_surprise": 7
    }"#;

    fn product_json() -> String {
        format!(
            r#"{{
            "id": "prd_1",
            "profile_id": "pro_1",
            "name": "Pro plan",
            "kind": "recurring",
            "status": "active",
            "prices": [{PRICE_JSON}],
            "aliases": [{{"id": "al_1", "alias": "PRO", "kind": "alias", "created_at": "2026-01-01T00:00:00Z"}}],
            "connector_references": [{{
                "id": "ref_1", "connector": "stripe", "merchant_connector_id": "mca_1",
                "connector_product_id": "prod_X", "mapping_mode": "manual_id",
                "created_at": "2026-01-01T00:00:00Z"
            }}],
            "addon_groups": [{{
                "id": "grp_1", "name": "Extras", "min_choices": 0, "max_choices": 2,
                "items": [{{"addon_product_id": "prd_a", "name": "Gift wrap", "status": "active"}}]
            }}],
            "bundle_items": [],
            "created_at": "2026-01-01T00:00:00Z",
            "modified_at": "2026-01-02T00:00:00Z",
            "category_id": "cat_1",
            "buyer_chooses_addons": false,
            "tax_category": "digital_services",
            "surprise_field": 1
        }}"#
        )
    }

    const CATEGORY_JSON: &str = r#"{
        "id": "cat_1",
        "profile_id": "pro_1",
        "name": "Plans",
        "position": 0,
        "status": "active",
        "created_at": "2026-01-01T00:00:00Z",
        "modified_at": "2026-01-01T00:00:00Z",
        "surprise_field": 1
    }"#;

    fn sync_json() -> String {
        r#"{
            "product_id": "prd_1",
            "status": "changed_at_provider",
            "links": [{
                "merchant_connector_id": "mca_1",
                "connector": "stripe",
                "connector_product_id": "prod_X",
                "test_mode": true,
                "status": "changed_at_provider",
                "differences": [{
                    "key": "k1",
                    "field": "name",
                    "catalog_value": "Pro plan",
                    "provider_value": "Pro",
                    "push_action": "update_product"
                }],
                "can_push": true,
                "compared_fields": ["name", "price_terms"]
            }],
            "checked_at": "2026-01-03T00:00:00Z",
            "surprise_field": 1
        }"#
        .to_string()
    }

    const COUNTS_JSON: &str = r#"{
        "new": 1, "changed": 0, "unchanged": 2, "unavailable": 0, "conflicting": 0,
        "products_created": 1, "prices_added": 1, "failed": 0
    }"#;

    const OUTCOME_JSON: &str = r#"{
        "merchant_connector_id": "mca_1",
        "connector": "stripe",
        "connector_product_id": "prod_X",
        "action": "archive",
        "status": "done",
        "deactivated_price_ids": ["price_X"],
        "kept_price_ids": [],
        "surprise_field": 1
    }"#;

    /// Pins method, URL and the shop header of the one request seen.
    fn assert_seen(mock: &crate::http::mock::MockTransport, method: &str, url: &str) {
        let seen = mock.seen.lock().unwrap();
        assert_eq!(seen.len(), 1);
        assert_eq!(seen[0].method, method);
        assert_eq!(seen[0].url, url);
        assert_eq!(seen[0].header("x-profile-id"), Some("pro_1"));
    }

    fn body(mock: &crate::http::mock::MockTransport) -> Value {
        mock.seen.lock().unwrap()[0].body_json()
    }

    fn assert_no_body(mock: &crate::http::mock::MockTransport) {
        assert!(mock.seen.lock().unwrap()[0].body.is_none());
    }

    #[tokio::test]
    async fn upload_image_posts_a_multipart_file_with_the_shop_header() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"image_url":"https://cdn.test/p.png","surprise_field":1}"#,
        )]);
        let out = client
            .products()
            .upload_image("pro_1", "p.png", "image/png", b"PNGDATA")
            .await
            .unwrap();
        assert_eq!(out.image_url, "https://cdn.test/p.png");
        assert_eq!(out.extra["surprise_field"], 1);

        assert_seen(&mock, "POST", "https://api.test/products/images");
        let seen = mock.seen.lock().unwrap();
        let content_type = seen[0].content_type.as_deref().expect("explicit type");
        let boundary = content_type
            .strip_prefix("multipart/form-data; boundary=")
            .expect("multipart content type");
        let raw = String::from_utf8(seen[0].body.clone().unwrap()).unwrap();
        assert!(raw.starts_with(&format!("--{boundary}\r\n")));
        assert!(raw.contains("name=\"file\"; filename=\"p.png\""));
        assert!(raw.contains("Content-Type: image/png\r\n\r\nPNGDATA\r\n"));
    }

    #[tokio::test]
    async fn create_posts_the_product_with_its_prices() {
        let (client, mock) = client_with(vec![Step::ok(&product_json())]);
        let params = ProductCreateRequest::new(
            "Pro plan",
            ProductKind::Recurring,
            vec![
                ProductPriceCreateRequest::new(1999, "EUR")
                    .recurring(ProductPriceInterval::Month, 1)
                    .trial(14, ProductPriceInterval::Day)
                    .is_default(true),
            ],
        )
        .product_id("pro-plan")
        .category_id("cat_1")
        .tax_category("digital_services");
        let product = client.products().create("pro_1", &params).await.unwrap();
        assert_eq!(product.id, "prd_1");
        assert_eq!(product.kind, ProductKind::Recurring);
        assert_eq!(product.prices[0].amount, 1999);
        assert_eq!(
            product.prices[0].billing_interval,
            Some(ProductPriceInterval::Month)
        );
        assert_eq!(product.prices[0].extra["price_surprise"], 7);
        assert_eq!(product.aliases[0].kind, ProductAliasKind::Alias);
        assert_eq!(
            product.connector_references[0].mapping_mode,
            ProductMappingMode::ManualId
        );
        assert_eq!(product.addon_groups[0].items[0].addon_product_id, "prd_a");
        assert_eq!(product.tax_category.as_deref(), Some("digital_services"));
        assert_eq!(product.extra["surprise_field"], 1);

        assert_seen(&mock, "POST", "https://api.test/products");
        assert_eq!(
            body(&mock),
            json!({
                "product_id": "pro-plan",
                "name": "Pro plan",
                "kind": "recurring",
                "prices": [{
                    "amount": 1999,
                    "currency": "EUR",
                    "billing_interval": "month",
                    "billing_interval_count": 1,
                    "trial_period": 14,
                    "trial_period_unit": "day",
                    "is_default": true
                }],
                "category_id": "cat_1",
                "tax_category": "digital_services"
            })
        );
    }

    #[tokio::test]
    async fn create_without_an_idempotency_key_is_not_replayed_on_a_5xx() {
        // A create carries no key, so a 5xx must surface rather than risk a
        // duplicate product. A mutation adding a key to this call fails here.
        let (client, mock) = client_with_retries(
            vec![
                Step::status(503, r#"{"error":{"message":"down"}}"#),
                Step::ok(&product_json()),
            ],
            2,
        );
        let params = ProductCreateRequest::new(
            "Pro plan",
            ProductKind::OneTime,
            vec![ProductPriceCreateRequest::new(500, "EUR")],
        );
        assert!(client.products().create("pro_1", &params).await.is_err());
        assert_eq!(mock.call_count(), 1);
        assert!(!mock.seen.lock().unwrap()[0].had_idempotency_key());
    }

    /// No catalogue route deduplicates on an `Idempotency-Key`, so a
    /// client-wide key is not sent and a `503` is not replayed into a second
    /// product. Mutation: call `request_with_headers(.., None, ..)` in `send`
    /// again — the header appears and the request count becomes 2.
    #[tokio::test]
    async fn create_ignores_a_client_wide_key_and_is_not_replayed() {
        let (client, mock) = client_with_retries(
            vec![
                Step::status(503, r#"{"error":{"message":"down"}}"#),
                Step::ok(&product_json()),
            ],
            2,
        );
        let params = ProductCreateRequest::new(
            "Pro plan",
            ProductKind::OneTime,
            vec![ProductPriceCreateRequest::new(500, "EUR")],
        );
        assert!(
            client
                .with_idempotency_key("client-key")
                .products()
                .create("pro_1", &params)
                .await
                .is_err()
        );
        assert_eq!(mock.call_count(), 1);
        assert!(!mock.seen.lock().unwrap()[0].had_idempotency_key());
    }

    /// The multipart upload has its own call site.
    #[tokio::test]
    async fn upload_image_ignores_a_client_wide_key_and_is_not_replayed() {
        let (client, mock) = client_with_retries(
            vec![
                Step::status(503, r#"{"error":{"message":"down"}}"#),
                Step::ok(r#"{"image_url":"https://cdn.test/p.png"}"#),
            ],
            2,
        );
        assert!(
            client
                .with_idempotency_key("client-key")
                .products()
                .upload_image("pro_1", "p.png", "image/png", b"PNGDATA")
                .await
                .is_err()
        );
        assert_eq!(mock.call_count(), 1);
        assert!(!mock.seen.lock().unwrap()[0].had_idempotency_key());
    }

    #[tokio::test]
    async fn list_sends_the_filters_as_query() {
        let (client, mock) = client_with(vec![Step::ok(&format!(
            r#"{{"data":[{}],"total_count":42,"surprise_field":1}}"#,
            product_json()
        ))]);
        let params = ProductListParams::new()
            .status(ProductStatus::Archived)
            .category_id("cat_1")
            .limit(10)
            .offset(20);
        let page = client.products().list("pro_1", &params).await.unwrap();
        assert_eq!(page.total_count, 42);
        assert_eq!(page.data[0].id, "prd_1");
        assert_eq!(page.extra["surprise_field"], 1);

        assert_seen(
            &mock,
            "GET",
            "https://api.test/products/list?status=archived&category_id=cat_1&limit=10&offset=20",
        );
    }

    #[tokio::test]
    async fn list_refuses_a_category_together_with_uncategorized() {
        let (client, mock) = client_with(vec![]);
        let params = ProductListParams::new()
            .category_id("cat_1")
            .uncategorized();
        match client.products().list("pro_1", &params).await.unwrap_err() {
            DelopayError::InvalidRequest(msg) => assert!(msg.contains("uncategorized")),
            other => panic!("expected InvalidRequest, got {other:?}"),
        }
        assert_eq!(mock.call_count(), 0);
    }

    #[tokio::test]
    async fn resolve_sends_only_the_chosen_lookup() {
        let (client, mock) = client_with(vec![Step::ok(&format!(
            r#"{{"matched_by":"connector_price","price_id":"price_1","product":{},"surprise_field":1}}"#,
            product_json()
        ))]);
        let out = client
            .products()
            .resolve(
                "pro_1",
                &ProductResolveQuery::connector_price("stripe", "price_X"),
            )
            .await
            .unwrap();
        assert_eq!(out.matched_by, ProductMatch::ConnectorPrice);
        assert_eq!(out.price_id.as_deref(), Some("price_1"));
        assert_eq!(out.product.id, "prd_1");
        assert_eq!(out.extra["surprise_field"], 1);

        assert_seen(
            &mock,
            "GET",
            "https://api.test/products/resolve?connector=stripe&connector_price_id=price_X",
        );
    }

    #[tokio::test]
    async fn retrieve_encodes_the_product_id() {
        let (client, mock) = client_with(vec![Step::ok(&product_json())]);
        let product = client.products().retrieve("prd/1", "pro_1").await.unwrap();
        assert_eq!(product.extra["surprise_field"], 1);
        assert_seen(&mock, "GET", "https://api.test/products/prd%2F1");
        assert_no_body(&mock);
    }

    #[tokio::test]
    async fn sales_sends_the_window_as_query() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{
                "product_id": "prd_1", "profile_id": "pro_1", "test_mode": false,
                "start_time": "2026-01-01T00:00:00Z", "end_time": "2026-02-01T00:00:00Z",
                "currencies": [{
                    "currency": "EUR", "payment_count": 3, "sold_quantity": 4,
                    "sold_amount": 8000, "refunded_quantity": 1, "refunded_amount": 2000,
                    "refund_pending_quantity": 0, "refund_pending_amount": 0,
                    "net_quantity": 3, "net_amount": 6000
                }],
                "surprise_field": 1
            }"#,
        )]);
        let params =
            ProductSalesParams::new("2026-01-01T00:00:00Z", false).end_time("2026-02-01T00:00:00Z");
        let out = client
            .products()
            .sales("prd_1", "pro_1", &params)
            .await
            .unwrap();
        assert_eq!(out.currencies[0].net_amount, 6000);
        assert_eq!(out.extra["surprise_field"], 1);

        assert_seen(
            &mock,
            "GET",
            "https://api.test/products/prd_1/sales?start_time=2026-01-01T00:00:00Z&end_time=2026-02-01T00:00:00Z&test_mode=false",
        );
    }

    #[tokio::test]
    async fn billing_readiness_joins_the_ids_into_one_value() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{
                "billing_account": {"merchant_connector_id": "mca_1", "connector": "stripe", "test_mode": true},
                "prices": [{"product_id": "prd_1", "price_id": "price_1", "state": "other_environment"}],
                "surprise_field": 1
            }"#,
        )]);
        let out = client
            .products()
            .billing_readiness("pro_1", &["prd_1", "prd_2"])
            .await
            .unwrap();
        assert_eq!(out.prices[0].state, PriceBillingState::OtherEnvironment);
        assert!(out.billing_account.unwrap().test_mode);
        assert_eq!(out.extra["surprise_field"], 1);

        // One comma-separated value, not repeated keys.
        assert_seen(
            &mock,
            "GET",
            "https://api.test/products/billing-readiness?product_ids=prd_1,prd_2",
        );
    }

    #[tokio::test]
    async fn update_posts_to_the_product_and_can_send_null_category() {
        let (client, mock) = client_with(vec![Step::ok(&product_json())]);
        let params = ProductUpdateRequest::new()
            .name("Pro")
            .uncategorized()
            .standard_tax_category();
        let product = client
            .products()
            .update("prd_1", "pro_1", &params)
            .await
            .unwrap();
        assert_eq!(product.extra["surprise_field"], 1);

        assert_seen(&mock, "POST", "https://api.test/products/prd_1");
        assert_eq!(
            body(&mock),
            json!({"name": "Pro", "category_id": null, "tax_category": null})
        );
    }

    #[tokio::test]
    async fn archive_posts_without_a_body() {
        let (client, mock) = client_with(vec![Step::ok(&product_json())]);
        let product = client.products().archive("prd_1", "pro_1").await.unwrap();
        assert_eq!(product.extra["surprise_field"], 1);
        assert_seen(&mock, "POST", "https://api.test/products/prd_1/archive");
        assert_no_body(&mock);
    }

    #[tokio::test]
    async fn restore_posts_without_a_body() {
        let (client, mock) = client_with(vec![Step::ok(&product_json())]);
        let product = client.products().restore("prd_1", "pro_1").await.unwrap();
        assert_eq!(product.extra["surprise_field"], 1);
        assert_seen(&mock, "POST", "https://api.test/products/prd_1/restore");
        assert_no_body(&mock);
    }

    #[tokio::test]
    async fn delete_deletes_the_product_and_accepts_a_json_body() {
        // Decoding the body as `()` fails here: the API answers with an object.
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"deleted":true,"product_id":"prd_1","surprise_field":1}"#,
        )]);
        client.products().delete("prd_1", "pro_1").await.unwrap();
        assert_seen(&mock, "DELETE", "https://api.test/products/prd_1");
        assert_no_body(&mock);
    }

    #[tokio::test]
    async fn delete_accepts_an_empty_body() {
        let (client, _mock) = client_with(vec![Step::ok("")]);
        client.products().delete("prd_1", "pro_1").await.unwrap();
    }

    #[tokio::test]
    async fn delete_with_providers_posts_the_provider_actions() {
        let (client, mock) = client_with(vec![Step::ok(&format!(
            r#"{{"product_id":"prd_1","deleted":true,"provider":[{OUTCOME_JSON}],"surprise_field":1}}"#
        ))]);
        let params = ProductDeleteRequest::new().provider_action(ProviderArchiveRequest::new(
            "mca_1",
            ProviderArchiveAction::Archive,
        ));
        let out = client
            .products()
            .delete_with_providers("prd_1", "pro_1", &params)
            .await
            .unwrap();
        assert!(out.deleted);
        assert_eq!(out.provider[0].status, ProviderArchiveStatus::Done);
        assert_eq!(out.provider[0].extra["surprise_field"], 1);
        assert_eq!(out.extra["surprise_field"], 1);

        assert_seen(&mock, "POST", "https://api.test/products/prd_1/delete");
        assert_eq!(
            body(&mock),
            json!({"provider_actions": [{"merchant_connector_id": "mca_1", "action": "archive"}]})
        );
    }

    #[tokio::test]
    async fn add_price_posts_the_price() {
        let (client, mock) = client_with(vec![Step::ok(&product_json())]);
        let params = ProductPriceCreateRequest::new(2999, "EUR").nickname("Yearly");
        let product = client
            .products()
            .add_price("prd_1", "pro_1", &params)
            .await
            .unwrap();
        assert_eq!(product.extra["surprise_field"], 1);
        assert_seen(&mock, "POST", "https://api.test/products/prd_1/prices");
        assert_eq!(
            body(&mock),
            json!({"nickname": "Yearly", "amount": 2999, "currency": "EUR"})
        );
    }

    #[tokio::test]
    async fn add_price_sends_tax_added_on_top_only_when_asked() {
        let (client, mock) = client_with(vec![Step::ok(&product_json())]);
        let params = ProductPriceCreateRequest::new(1000, "EUR")
            .recurring(ProductPriceInterval::Month, 1)
            .tax_behavior(ProductPriceTaxBehavior::Exclusive);
        client
            .products()
            .add_price("prd_1", "pro_1", &params)
            .await
            .unwrap();
        assert_eq!(
            body(&mock),
            json!({"amount": 1000, "currency": "EUR", "billing_interval": "month",
                   "billing_interval_count": 1, "tax_behavior": "exclusive"})
        );
    }

    #[test]
    fn a_price_reads_whether_tax_is_added_on_top() {
        let with = |value: &str| -> ProductPriceResponse {
            let mut json: Value = serde_json::from_str(PRICE_JSON).unwrap();
            json["tax_behavior"] = json!(value);
            serde_json::from_value(json).unwrap()
        };
        assert_eq!(
            with("exclusive").tax_behavior,
            Some(ProductPriceTaxBehavior::Exclusive)
        );
        assert_eq!(
            with("inclusive").tax_behavior,
            Some(ProductPriceTaxBehavior::Inclusive)
        );
        assert_eq!(
            with("a_later_mode").tax_behavior,
            Some(ProductPriceTaxBehavior::Unknown)
        );
        let older: ProductPriceResponse = serde_json::from_str(PRICE_JSON).unwrap();
        assert_eq!(older.tax_behavior, None);
    }

    #[tokio::test]
    async fn update_price_encodes_both_ids() {
        let (client, mock) = client_with(vec![Step::ok(&product_json())]);
        let params = ProductPriceUpdateRequest::new().is_default(false);
        let product = client
            .products()
            .update_price("prd_1", "price/1", "pro_1", &params)
            .await
            .unwrap();
        assert_eq!(product.extra["surprise_field"], 1);
        assert_seen(
            &mock,
            "POST",
            "https://api.test/products/prd_1/prices/price%2F1",
        );
        assert_eq!(body(&mock), json!({"is_default": false}));
    }

    #[tokio::test]
    async fn archive_price_posts_the_archive_sub_path() {
        let (client, mock) = client_with(vec![Step::ok(&product_json())]);
        let product = client
            .products()
            .archive_price("prd_1", "price_1", "pro_1")
            .await
            .unwrap();
        assert_eq!(product.extra["surprise_field"], 1);
        assert_seen(
            &mock,
            "POST",
            "https://api.test/products/prd_1/prices/price_1/archive",
        );
        assert_no_body(&mock);
    }

    #[tokio::test]
    async fn create_addon_group_posts_the_group() {
        let (client, mock) = client_with(vec![Step::ok(&product_json())]);
        let params = AddonGroupCreateRequest::new("Extras", 0, 2, vec!["prd_a".to_string()]);
        let product = client
            .products()
            .create_addon_group("prd_1", "pro_1", &params)
            .await
            .unwrap();
        assert_eq!(product.addon_groups[0].max_choices, 2);
        assert_eq!(product.extra["surprise_field"], 1);
        assert_seen(
            &mock,
            "POST",
            "https://api.test/products/prd_1/addon-groups",
        );
        assert_eq!(
            body(&mock),
            json!({"name": "Extras", "min_choices": 0, "max_choices": 2, "addon_product_ids": ["prd_a"]})
        );
    }

    #[tokio::test]
    async fn update_addon_group_posts_to_the_group() {
        let (client, mock) = client_with(vec![Step::ok(&product_json())]);
        let params = AddonGroupUpdateRequest::new()
            .choices(1, 1)
            .addon_product_ids(vec!["prd_b".to_string()]);
        let product = client
            .products()
            .update_addon_group("prd_1", "grp 1", "pro_1", &params)
            .await
            .unwrap();
        assert_eq!(product.extra["surprise_field"], 1);
        assert_seen(
            &mock,
            "POST",
            "https://api.test/products/prd_1/addon-groups/grp%201",
        );
        assert_eq!(
            body(&mock),
            json!({"min_choices": 1, "max_choices": 1, "addon_product_ids": ["prd_b"]})
        );
    }

    #[tokio::test]
    async fn delete_addon_group_deletes_the_group() {
        let (client, mock) = client_with(vec![Step::ok(&product_json())]);
        let product = client
            .products()
            .delete_addon_group("prd_1", "grp_1", "pro_1")
            .await
            .unwrap();
        assert_eq!(product.extra["surprise_field"], 1);
        assert_seen(
            &mock,
            "DELETE",
            "https://api.test/products/prd_1/addon-groups/grp_1",
        );
        assert_no_body(&mock);
    }

    #[tokio::test]
    async fn replace_bundle_posts_the_definition() {
        let (client, mock) = client_with(vec![Step::ok(&product_json())]);
        let params = BundleDefinition::new(
            BundlePricing::Sum,
            vec![
                BundleItemRequest::new("prd_a").quantity(2),
                BundleItemRequest::new("prd_b"),
            ],
        );
        let product = client
            .products()
            .replace_bundle("prd_1", "pro_1", &params)
            .await
            .unwrap();
        assert_eq!(product.extra["surprise_field"], 1);
        assert_seen(&mock, "POST", "https://api.test/products/prd_1/bundle");
        assert_eq!(
            body(&mock),
            json!({"pricing": "sum", "items": [{"product_id": "prd_a", "quantity": 2}, {"product_id": "prd_b"}]})
        );
    }

    #[tokio::test]
    async fn add_alias_posts_the_name() {
        let (client, mock) = client_with(vec![Step::ok(&product_json())]);
        let product = client
            .products()
            .add_alias("prd_1", "pro_1", &ProductAliasCreateRequest::new("PRO"))
            .await
            .unwrap();
        assert_eq!(product.extra["surprise_field"], 1);
        assert_seen(&mock, "POST", "https://api.test/products/prd_1/aliases");
        assert_eq!(body(&mock), json!({"alias": "PRO"}));
    }

    #[tokio::test]
    async fn remove_alias_posts_the_remove_sub_path() {
        let (client, mock) = client_with(vec![Step::ok(&product_json())]);
        let product = client
            .products()
            .remove_alias("prd_1", "al/1", "pro_1")
            .await
            .unwrap();
        assert_eq!(product.extra["surprise_field"], 1);
        assert_seen(
            &mock,
            "POST",
            "https://api.test/products/prd_1/aliases/al%2F1/remove",
        );
        assert_no_body(&mock);
    }

    #[tokio::test]
    async fn add_connector_reference_posts_the_reference() {
        let (client, mock) = client_with(vec![Step::ok(&product_json())]);
        let params = ProductConnectorReferenceCreateRequest::new("mca_1", "prod_X")
            .price("price_X", "price_1")
            .display_name("Pro");
        let product = client
            .products()
            .add_connector_reference("prd_1", "pro_1", &params)
            .await
            .unwrap();
        assert_eq!(product.extra["surprise_field"], 1);
        assert_seen(
            &mock,
            "POST",
            "https://api.test/products/prd_1/connector-references",
        );
        assert_eq!(
            body(&mock),
            json!({
                "merchant_connector_id": "mca_1",
                "connector_product_id": "prod_X",
                "connector_price_id": "price_X",
                "price_id": "price_1",
                "display_name": "Pro"
            })
        );
    }

    #[tokio::test]
    async fn remove_connector_reference_posts_the_remove_sub_path() {
        let (client, mock) = client_with(vec![Step::ok(&product_json())]);
        let product = client
            .products()
            .remove_connector_reference("prd_1", "ref_1", "pro_1")
            .await
            .unwrap();
        assert_eq!(product.extra["surprise_field"], 1);
        assert_seen(
            &mock,
            "POST",
            "https://api.test/products/prd_1/connector-references/ref_1/remove",
        );
        assert_no_body(&mock);
    }

    #[tokio::test]
    async fn import_suggestions_sends_the_page_as_query() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"[{
                "item_id": "prod_X", "name": "Pro", "available": true,
                "price_id": [{"price_id": "price_X", "amount": 1999, "currency": "EUR",
                              "interval": "Month", "interval_count": 1}],
                "surprise_field": 1
            }]"#,
        )]);
        let params = ProductImportSuggestionsParams::new("mca_1")
            .limit(5)
            .offset(10);
        let items = client
            .products()
            .import_suggestions("pro_1", &params)
            .await
            .unwrap();
        assert_eq!(items[0].item_id, "prod_X");
        assert_eq!(items[0].available, Some(true));
        assert_eq!(items[0].extra["surprise_field"], 1);

        assert_seen(
            &mock,
            "GET",
            "https://api.test/products/import-suggestions?merchant_connector_id=mca_1&limit=5&offset=10",
        );
    }

    #[tokio::test]
    async fn accept_import_posts_the_item_and_its_page() {
        let (client, mock) = client_with(vec![Step::ok(&product_json())]);
        let params = ProductImportAcceptRequest::new("mca_1", "prod_X").page(20, 0);
        let product = client
            .products()
            .accept_import("prd_1", "pro_1", &params)
            .await
            .unwrap();
        assert_eq!(product.extra["surprise_field"], 1);
        assert_seen(
            &mock,
            "POST",
            "https://api.test/products/prd_1/connector-references/import",
        );
        assert_eq!(
            body(&mock),
            json!({"merchant_connector_id": "mca_1", "connector_product_id": "prod_X", "limit": 20, "offset": 0})
        );
    }

    #[tokio::test]
    async fn create_category_posts_the_name() {
        let (client, mock) = client_with(vec![Step::ok(CATEGORY_JSON)]);
        let category = client
            .products()
            .create_category("pro_1", &ProductCategoryCreateRequest::new("Plans"))
            .await
            .unwrap();
        assert_eq!(category.id, "cat_1");
        assert_eq!(category.status, ProductStatus::Active);
        assert_eq!(category.extra["surprise_field"], 1);
        assert_seen(&mock, "POST", "https://api.test/products/categories");
        assert_eq!(body(&mock), json!({"name": "Plans"}));
    }

    #[tokio::test]
    async fn list_categories_sends_include_archived() {
        let (client, mock) = client_with(vec![Step::ok(&format!(
            r#"{{"data":[{CATEGORY_JSON}],"surprise_field":1}}"#
        ))]);
        let out = client
            .products()
            .list_categories(
                "pro_1",
                &ProductCategoryListParams::new().include_archived(true),
            )
            .await
            .unwrap();
        assert_eq!(out.data[0].position, 0);
        assert_eq!(out.extra["surprise_field"], 1);
        assert_seen(
            &mock,
            "GET",
            "https://api.test/products/categories/list?include_archived=true",
        );
    }

    #[tokio::test]
    async fn reorder_categories_posts_the_order() {
        let (client, mock) = client_with(vec![Step::ok(&format!(
            r#"{{"data":[{CATEGORY_JSON}],"surprise_field":1}}"#
        ))]);
        let params = ProductCategoryReorderRequest::new(vec!["cat_2".into(), "cat_1".into()]);
        let out = client
            .products()
            .reorder_categories("pro_1", &params)
            .await
            .unwrap();
        assert_eq!(out.extra["surprise_field"], 1);
        assert_seen(
            &mock,
            "POST",
            "https://api.test/products/categories/reorder",
        );
        assert_eq!(body(&mock), json!({"category_ids": ["cat_2", "cat_1"]}));
    }

    #[tokio::test]
    async fn update_category_encodes_the_category_id() {
        let (client, mock) = client_with(vec![Step::ok(CATEGORY_JSON)]);
        let category = client
            .products()
            .update_category(
                "cat/1",
                "pro_1",
                &ProductCategoryUpdateRequest::new().name("Bundles"),
            )
            .await
            .unwrap();
        assert_eq!(category.extra["surprise_field"], 1);
        assert_seen(
            &mock,
            "POST",
            "https://api.test/products/categories/cat%2F1",
        );
        assert_eq!(body(&mock), json!({"name": "Bundles"}));
    }

    #[tokio::test]
    async fn delete_category_deletes_and_decodes_the_category() {
        let (client, mock) = client_with(vec![Step::ok(CATEGORY_JSON)]);
        let category = client
            .products()
            .delete_category("cat_1", "pro_1")
            .await
            .unwrap();
        assert_eq!(category.extra["surprise_field"], 1);
        assert_seen(
            &mock,
            "DELETE",
            "https://api.test/products/categories/cat_1",
        );
        assert_no_body(&mock);
    }

    #[tokio::test]
    async fn archive_category_posts_the_archive_sub_path() {
        let (client, mock) = client_with(vec![Step::ok(CATEGORY_JSON)]);
        let category = client
            .products()
            .archive_category("cat_1", "pro_1")
            .await
            .unwrap();
        assert_eq!(category.extra["surprise_field"], 1);
        assert_seen(
            &mock,
            "POST",
            "https://api.test/products/categories/cat_1/archive",
        );
        assert_no_body(&mock);
    }

    #[tokio::test]
    async fn restore_category_posts_the_restore_sub_path() {
        let (client, mock) = client_with(vec![Step::ok(CATEGORY_JSON)]);
        let category = client
            .products()
            .restore_category("cat_1", "pro_1")
            .await
            .unwrap();
        assert_eq!(category.extra["surprise_field"], 1);
        assert_seen(
            &mock,
            "POST",
            "https://api.test/products/categories/cat_1/restore",
        );
        assert_no_body(&mock);
    }

    #[tokio::test]
    async fn import_preview_posts_the_scope_and_options() {
        let (client, mock) = client_with(vec![Step::ok(&format!(
            r#"{{
                "confirmation": "conf_1",
                "capabilities": {{"connector": "stripe", "one_time_products": true,
                    "recurring_products": true, "availability": true, "trial_periods": false}},
                "counts": {COUNTS_JSON},
                "items": [{{
                    "key": "k1", "connector_product_id": "prod_X", "mixed": false,
                    "name": "Pro", "classification": "new", "kind": "recurring",
                    "prices": [{{"connector_price_id": "price_X", "amount": 1999,
                        "currency": "EUR", "interval": "month", "interval_count": 1, "state": "new"}}]
                }}],
                "surprise_field": 1
            }}"#
        ))]);
        let params = ProductImportPreviewRequest::new("mca_1")
            .scopes(vec![ProductImportScope::ProductsRecurring])
            .options(ProductImportOptions::new().mixed(ProductImportMixedDecision::RecurringOnly));
        let out = client
            .products()
            .import_preview("pro_1", &params)
            .await
            .unwrap();
        assert_eq!(out.confirmation, "conf_1");
        assert_eq!(
            out.items[0].classification,
            ProductImportClassification::New
        );
        assert_eq!(out.counts.unchanged, 2);
        assert_eq!(out.counts.archived, None);
        assert_eq!(out.extra["surprise_field"], 1);

        assert_seen(&mock, "POST", "https://api.test/products/import/preview");
        assert_eq!(
            body(&mock),
            json!({
                "merchant_connector_id": "mca_1",
                "scopes": ["products_recurring"],
                "options": {"mixed": "recurring_only"}
            })
        );
    }

    fn run_json() -> String {
        format!(
            r#"{{
                "id": "run_1", "merchant_connector_id": "mca_1", "connector": "stripe",
                "status": "partial", "confirmation_outdated": false,
                "counts": {COUNTS_JSON},
                "failures": [{{"connector_product_id": "prod_Y", "kind": "one_time",
                    "name": "Mug", "reason": "currency not supported"}}],
                "created_at": "2026-01-01T00:00:00Z",
                "surprise_field": 1
            }}"#
        )
    }

    #[tokio::test]
    async fn import_apply_posts_the_confirmation_and_decisions() {
        let (client, mock) = client_with(vec![Step::ok(&run_json())]);
        let params = ProductImportApplyRequest::new("mca_1")
            .confirmation("conf_1")
            .decision("prod_X", ProductImportMixedDecision::Split)
            .options(
                ProductImportOptions::new().archived(ProductImportArchivedAtProvider::Archive),
            );
        let run = client
            .products()
            .import_apply("pro_1", &params)
            .await
            .unwrap();
        assert_eq!(run.status, "partial");
        assert_eq!(run.failures[0].kind, Some(ProductKind::OneTime));
        assert_eq!(run.extra["surprise_field"], 1);

        assert_seen(&mock, "POST", "https://api.test/products/import/apply");
        assert_eq!(
            body(&mock),
            json!({
                "merchant_connector_id": "mca_1",
                "confirmation": "conf_1",
                "decisions": {"prod_X": "split"},
                "options": {"archived": "archive"}
            })
        );
    }

    #[tokio::test]
    async fn list_import_runs_sends_the_account_as_query() {
        let (client, mock) = client_with(vec![Step::ok(&format!(
            r#"{{"data":[{}],"surprise_field":1}}"#,
            run_json()
        ))]);
        let out = client
            .products()
            .list_import_runs("pro_1", "mca_1")
            .await
            .unwrap();
        assert_eq!(out.data[0].id, "run_1");
        assert_eq!(out.extra["surprise_field"], 1);
        assert_seen(
            &mock,
            "GET",
            "https://api.test/products/import/runs?merchant_connector_id=mca_1",
        );
    }

    #[tokio::test]
    async fn provider_sync_gets_the_comparison() {
        let (client, mock) = client_with(vec![Step::ok(&sync_json())]);
        let out = client
            .products()
            .provider_sync("prd_1", "pro_1")
            .await
            .unwrap();
        assert_eq!(out.status, ProviderSyncStatus::ChangedAtProvider);
        let link = &out.links[0];
        assert_eq!(link.differences[0].field, ProviderSyncField::Name);
        assert_eq!(
            link.differences[0].push_action,
            Some(ProviderPushAction::UpdateProduct)
        );
        assert_eq!(link.compared_fields[1], ProviderSyncField::PriceTerms);
        assert_eq!(link.can_create, None);
        assert_eq!(out.extra["surprise_field"], 1);

        assert_seen(
            &mock,
            "GET",
            "https://api.test/products/prd_1/provider-sync",
        );
    }

    #[tokio::test]
    async fn provider_sync_reads_the_wire_unknown_status_as_unknown() {
        // `unknown` is a real status on the wire (the provider could not be
        // read); a value the SDK does not know lands in `Unrecognized`.
        let (client, _mock) = client_with(vec![Step::ok(
            r#"{"product_id":"prd_1","status":"unknown","links":[],"checked_at":"t"}"#,
        )]);
        let out = client
            .products()
            .provider_sync("prd_1", "pro_1")
            .await
            .unwrap();
        assert_eq!(out.status, ProviderSyncStatus::Unknown);

        let (client, _mock) = client_with(vec![Step::ok(
            r#"{"product_id":"prd_1","status":"brand_new","links":[],"checked_at":"t"}"#,
        )]);
        let out = client
            .products()
            .provider_sync("prd_1", "pro_1")
            .await
            .unwrap();
        assert_eq!(out.status, ProviderSyncStatus::Unrecognized);
    }

    #[tokio::test]
    async fn provider_sync_batch_posts_the_ids() {
        let (client, mock) = client_with(vec![Step::ok(&format!(
            r#"{{"data":[{}],"surprise_field":1}}"#,
            sync_json()
        ))]);
        let params = ProductProviderSyncBatchRequest::new(vec!["prd_1".into(), "prd_2".into()]);
        let out = client
            .products()
            .provider_sync_batch("pro_1", &params)
            .await
            .unwrap();
        assert_eq!(out.data[0].product_id, "prd_1");
        assert_eq!(out.extra["surprise_field"], 1);
        assert_seen(&mock, "POST", "https://api.test/products/provider-sync");
        assert_eq!(body(&mock), json!({"product_ids": ["prd_1", "prd_2"]}));
    }

    #[tokio::test]
    async fn provider_push_posts_the_confirmed_keys() {
        let (client, mock) = client_with(vec![Step::ok(&format!(
            r#"{{
                "nothing_to_push": false, "confirmation_outdated": false,
                "applied": [{{"action": "replace_price", "keys": ["k2"], "price_id": "price_1",
                    "connector_price_id": "price_Z"}}],
                "result": {},
                "surprise_field": 1
            }}"#,
            sync_json()
        ))]);
        let params = ProductProviderPushRequest::new("mca_1", vec!["k2".into()]);
        let out = client
            .products()
            .provider_push("prd_1", "pro_1", &params)
            .await
            .unwrap();
        assert_eq!(out.applied[0].action, ProviderPushAction::ReplacePrice);
        assert_eq!(out.result.product_id, "prd_1");
        assert_eq!(out.extra["surprise_field"], 1);
        assert_seen(
            &mock,
            "POST",
            "https://api.test/products/prd_1/provider-sync/push",
        );
        assert_eq!(
            body(&mock),
            json!({"merchant_connector_id": "mca_1", "confirmed": ["k2"]})
        );
    }

    #[tokio::test]
    async fn provider_accounts_gets_the_accounts() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"data":[{
                "merchant_connector_id": "mca_1", "connector": "paypal", "test_mode": false,
                "disabled": false, "billing_processor": true, "serves_subscriptions": true,
                "capabilities": {"read_catalog": true, "one_time_products": false,
                    "recurring_products": true, "push": false, "create": true,
                    "archive": "none", "split_mixed_imports": false,
                    "unavailable_reason": "no_credentials_for_environment",
                    "unavailable_environment": "test"}
            }],"surprise_field":1}"#,
        )]);
        let out = client.products().provider_accounts("pro_1").await.unwrap();
        let caps = &out.data[0].capabilities;
        assert_eq!(caps.archive, ProviderArchiveMode::NoAction);
        assert_eq!(
            caps.unavailable_reason,
            Some(crate::core::models::product::ProviderUnavailableReason::NoCredentialsForEnvironment)
        );
        assert!(out.data[0].billing_processor);
        assert_eq!(out.extra["surprise_field"], 1);
        assert_seen(&mock, "GET", "https://api.test/products/provider-accounts");
        assert_no_body(&mock);
    }

    #[tokio::test]
    async fn provider_cleanups_gets_the_pending_cleanups() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{"data":[{
                "product_id": "prd_1", "product_name": "Pro", "deleted": true,
                "merchant_connector_id": "mca_1", "connector": "stripe",
                "connector_product_id": "prod_X", "action": "deactivate_plans",
                "error": "timeout", "surprise_field": 1
            }],"surprise_field":1}"#,
        )]);
        let out = client.products().provider_cleanups("pro_1").await.unwrap();
        assert_eq!(out.data[0].action, ProviderArchiveAction::DeactivatePlans);
        assert_eq!(out.data[0].attempted_at, None);
        assert_eq!(out.data[0].extra["surprise_field"], 1);
        assert_eq!(out.extra["surprise_field"], 1);
        assert_seen(&mock, "GET", "https://api.test/products/provider-cleanups");
    }

    #[tokio::test]
    async fn provider_create_posts_the_confirmed_plan() {
        let (client, mock) = client_with(vec![Step::ok(
            r#"{
                "created": true, "confirmation_outdated": false,
                "plan": {"fingerprint": "fp_1", "connector": "stripe",
                    "merchant_connector_id": "mca_1", "test_mode": true, "name": "Pro",
                    "prices": [{"price_id": "price_1", "is_default": true,
                        "terms": {"amount": 1999, "currency": "EUR", "interval": "month",
                            "interval_count": 1, "active": true}}],
                    "unsupported_prices": [], "skipped_price_ids": []},
                "connector_product_id": "prod_N",
                "prices": [{"price_id": "price_1", "connector_price_id": "price_N"}],
                "surprise_field": 1
            }"#,
        )]);
        let params = ProductProviderCreateRequest::new("mca_1")
            .price_ids(vec!["price_1".into()])
            .confirmed("fp_1");
        let out = client
            .products()
            .provider_create("prd_1", "pro_1", &params)
            .await
            .unwrap();
        assert!(out.created);
        assert_eq!(out.plan.prices[0].terms.amount, 1999);
        assert_eq!(out.connector_product_id.as_deref(), Some("prod_N"));
        assert!(out.result.is_none());
        assert_eq!(out.extra["surprise_field"], 1);
        assert_seen(
            &mock,
            "POST",
            "https://api.test/products/prd_1/provider-sync/create",
        );
        assert_eq!(
            body(&mock),
            json!({"merchant_connector_id": "mca_1", "price_ids": ["price_1"], "confirmed": "fp_1"})
        );
    }

    #[tokio::test]
    async fn provider_archive_posts_the_action() {
        let (client, mock) = client_with(vec![Step::ok(OUTCOME_JSON)]);
        let params = ProviderArchiveRequest::new("mca_1", ProviderArchiveAction::Archive)
            .connector_product_id("prod_X");
        let out = client
            .products()
            .provider_archive("prd_1", "pro_1", &params)
            .await
            .unwrap();
        assert_eq!(out.action, ProviderArchiveAction::Archive);
        assert_eq!(out.deactivated_price_ids, ["price_X"]);
        assert_eq!(out.extra["surprise_field"], 1);
        assert_seen(
            &mock,
            "POST",
            "https://api.test/products/prd_1/provider-archive",
        );
        assert_eq!(
            body(&mock),
            json!({"merchant_connector_id": "mca_1", "action": "archive", "connector_product_id": "prod_X"})
        );
    }

    #[test]
    fn product_status_query_values_match_the_wire() {
        // `as_str` feeds the list query; it must spell what serde writes.
        for status in [ProductStatus::Active, ProductStatus::Archived] {
            assert_eq!(
                serde_json::to_value(status).unwrap(),
                json!(status.as_str())
            );
        }
    }
}