unifi-cli 0.3.4

CLI for UniFi Network controller
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
use wiremock::matchers::{body_json, method, path, path_regex};
use wiremock::{Mock, MockServer, ResponseTemplate};

// Helper to create a UnifiClient pointing at the mock server
async fn mock_client(server: &MockServer) -> unifi_cli::api::UnifiClient {
    unifi_cli::api::UnifiClient::new(&server.uri(), "test-api-key").unwrap()
}

// Mount the site discovery endpoint that ensure_site_id() calls
async fn mount_site_discovery(server: &MockServer) {
    Mock::given(method("GET"))
        .and(path("/proxy/network/integration/v1/sites"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "offset": 0,
            "limit": 25,
            "count": 1,
            "totalCount": 1,
            "data": [{"id": "test-site-uuid"}]
        })))
        .expect(1..)
        .mount(server)
        .await;
}

/// Run the real `unifi` binary against `server` and return the JSON it printed.
///
/// Driving the binary rather than calling the command function is what makes a
/// schema check meaningful: it inspects the bytes a caller actually receives.
async fn run_json(server: &MockServer, args: &[&str]) -> serde_json::Value {
    let uri = server.uri();
    let mut argv = vec!["--host", uri.as_str(), "--api-key", "test-key"];
    argv.extend_from_slice(args);
    argv.extend_from_slice(&["--output", "json"]);
    let output = std::process::Command::new(env!("CARGO_BIN_EXE_unifi"))
        .args(&argv)
        .output()
        .expect("failed to run the unifi binary");
    assert!(
        output.status.success(),
        "{} failed: {}",
        args.join(" "),
        String::from_utf8_lossy(&output.stderr)
    );
    serde_json::from_slice(&output.stdout).unwrap_or_else(|e| {
        panic!(
            "stdout of `{}` was not valid JSON ({e}): {}",
            args.join(" "),
            String::from_utf8_lossy(&output.stdout)
        )
    })
}

/// The one record whose keys `output_fields` describes.
///
/// A list command wraps its records in a pagination envelope, `devices ports`
/// and `system health` emit a bare array, and a detail command emits the record
/// on its own. The schema describes a record in every case.
fn one_record(command: &str, body: &serde_json::Value) -> serde_json::Value {
    let record = match body {
        serde_json::Value::Array(items) => items.first(),
        serde_json::Value::Object(fields) => match fields.get("items") {
            Some(serde_json::Value::Array(items)) => items.first(),
            _ => Some(body),
        },
        _ => None,
    };
    record
        .unwrap_or_else(|| panic!("`{command}` emitted no record to check against: {body}"))
        .clone()
}

/// Assert `unifi schema` declares for `command` exactly the keys the command
/// emits: no undiscoverable field, and no documented field that never appears.
///
/// For an agent-facing CLI the schema is the contract, and nothing else in this
/// suite would catch the two halves drifting apart. Each command that publishes
/// `output_fields` gets one of these; the check lives here once so adding it to
/// a command costs a single call.
fn assert_schema_matches(command: &str, body: &serde_json::Value) {
    let record = one_record(command, body);
    let emitted = record
        .as_object()
        .unwrap_or_else(|| panic!("`{command}` must emit a JSON object: {body}"));

    let schema_output = std::process::Command::new(env!("CARGO_BIN_EXE_unifi"))
        .arg("schema")
        .output()
        .expect("failed to run unifi schema");
    let schema: serde_json::Value =
        serde_json::from_slice(&schema_output.stdout).expect("unifi schema must print valid JSON");
    let entry = schema["commands"]
        .as_array()
        .expect("schema must have a commands array")
        .iter()
        .find(|c| c["name"] == command)
        .unwrap_or_else(|| panic!("schema must publish a \"{command}\" command"));

    let mut declared: Vec<&str> = entry["output_fields"]
        .as_array()
        .unwrap_or_else(|| panic!("`{command}` must declare output_fields"))
        .iter()
        .map(|f| f["name"].as_str().expect("output field must have a name"))
        .collect();
    declared.sort_unstable();
    let mut actual: Vec<&str> = emitted.keys().map(String::as_str).collect();
    actual.sort_unstable();
    assert_eq!(
        actual, declared,
        "`{command}` output_fields in the schema must exactly match the keys it emits"
    );
}

// --- UnifiClient API tests ---

mod client_api {
    use super::*;

    #[tokio::test]
    async fn list_clients_returns_paginated_results() {
        let server = MockServer::start().await;
        mount_site_discovery(&server).await;

        Mock::given(method("GET"))
            .and(path_regex(r"/proxy/network/integration/v1/sites/.*/clients"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "offset": 0, "limit": 200, "count": 2, "totalCount": 2,
                "data": [
                    {"macAddress": "aa:bb:cc:dd:ee:ff", "ipAddress": "192.0.2.1", "name": "Device1", "type": "WIRED"},
                    {"macAddress": "11:22:33:44:55:66", "ipAddress": "192.0.2.2", "hostname": "host2", "type": "WIRELESS"}
                ]
            })))
            .mount(&server)
            .await;

        let mut client = mock_client(&server).await;
        let clients = client.list_clients().await.unwrap();
        assert_eq!(clients.len(), 2);
        assert_eq!(clients[0].name.as_deref(), Some("Device1"));
        assert_eq!(clients[1].hostname.as_deref(), Some("host2"));
    }

    #[tokio::test]
    async fn list_clients_handles_pagination() {
        let server = MockServer::start().await;
        mount_site_discovery(&server).await;

        // First page
        Mock::given(method("GET"))
            .and(path_regex(
                r"/proxy/network/integration/v1/sites/.*/clients",
            ))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "offset": 0, "limit": 200, "count": 200, "totalCount": 201,
                "data": (0..200).map(|i| serde_json::json!({
                    "macAddress": format!("aa:bb:cc:dd:{:02x}:{:02x}", i / 256, i % 256),
                    "type": "WIRED"
                })).collect::<Vec<_>>()
            })))
            .up_to_n_times(1)
            .mount(&server)
            .await;

        // Second page
        Mock::given(method("GET"))
            .and(path_regex(
                r"/proxy/network/integration/v1/sites/.*/clients",
            ))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "offset": 200, "limit": 200, "count": 1, "totalCount": 201,
                "data": [{"macAddress": "ff:ff:ff:ff:ff:ff", "type": "WIRED"}]
            })))
            .mount(&server)
            .await;

        let mut client = mock_client(&server).await;
        let clients = client.list_clients().await.unwrap();
        assert_eq!(clients.len(), 201);
    }

    #[tokio::test]
    async fn get_client_detail_finds_by_mac() {
        let server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/sta"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [
                    {"_id": "abc", "mac": "aa:bb:cc:dd:ee:ff", "ip": "192.0.2.1", "name": "Target", "is_wired": true, "uptime": 7200},
                    {"_id": "def", "mac": "11:22:33:44:55:66", "ip": "192.0.2.2"}
                ]
            })))
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        let detail = client.get_client_detail("AA:BB:CC:DD:EE:FF").await.unwrap();
        assert_eq!(detail.display_name(), "Target");
        assert!(detail.is_wired);
        assert_eq!(detail.uptime, Some(7200));
    }

    #[tokio::test]
    async fn get_client_detail_not_found() {
        let server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/sta"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [
                    {"_id": "abc", "mac": "aa:bb:cc:dd:ee:ff"}
                ]
            })))
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        let err = client
            .get_client_detail("00:00:00:00:00:00")
            .await
            .unwrap_err();
        assert!(err.to_string().contains("Not found"));
    }

    #[tokio::test]
    async fn get_client_detail_accepts_dash_format() {
        let server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/sta"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [{"_id": "abc", "mac": "aa:bb:cc:dd:ee:ff", "name": "Found"}]
            })))
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        let detail = client.get_client_detail("AA-BB-CC-DD-EE-FF").await.unwrap();
        assert_eq!(detail.display_name(), "Found");
    }

    #[tokio::test]
    async fn set_fixed_ip_via_put() {
        let server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/sta"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [{"_id": "client123", "mac": "aa:bb:cc:dd:ee:ff"}]
            })))
            .mount(&server)
            .await;

        Mock::given(method("PUT"))
            .and(path("/proxy/network/api/s/default/rest/user/client123"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [{}]
            })))
            .expect(1)
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        client
            .set_fixed_ip("aa:bb:cc:dd:ee:ff", "192.0.2.50", None)
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn set_fixed_ip_falls_back_to_post_on_404() {
        let server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/sta"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [{"_id": "newclient", "mac": "aa:bb:cc:dd:ee:ff"}]
            })))
            .mount(&server)
            .await;

        // PUT returns 404 (no existing user entry)
        Mock::given(method("PUT"))
            .and(path("/proxy/network/api/s/default/rest/user/newclient"))
            .respond_with(ResponseTemplate::new(404).set_body_json(serde_json::json!({
                "meta": {"rc": "error", "msg": "api.err.ObjectNotFound"},
                "data": []
            })))
            .expect(1)
            .mount(&server)
            .await;

        // POST creates the user entry
        Mock::given(method("POST"))
            .and(path("/proxy/network/api/s/default/rest/user"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [{}]
            })))
            .expect(1)
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        client
            .set_fixed_ip("aa:bb:cc:dd:ee:ff", "192.0.2.99", Some("NewDevice"))
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn set_fixed_ip_client_not_found() {
        let server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/sta"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": []
            })))
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        let err = client
            .set_fixed_ip("00:00:00:00:00:00", "192.0.2.1", None)
            .await
            .unwrap_err();
        assert!(err.to_string().contains("Not found"));
    }

    #[tokio::test]
    async fn block_client_sends_correct_command() {
        let server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/proxy/network/api/s/default/cmd/stamgr"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": []
            })))
            .expect(1)
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        client.block_client("AABBCCDDEEFF").await.unwrap();
    }

    #[tokio::test]
    async fn unblock_client_sends_correct_command() {
        let server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/proxy/network/api/s/default/cmd/stamgr"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": []
            })))
            .expect(1)
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        client.unblock_client("aa:bb:cc:dd:ee:ff").await.unwrap();
    }

    #[tokio::test]
    async fn kick_client_sends_correct_command() {
        let server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/proxy/network/api/s/default/cmd/stamgr"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": []
            })))
            .expect(1)
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        client.kick_client("aa:bb:cc:dd:ee:ff").await.unwrap();
    }

    #[tokio::test]
    async fn list_devices_returns_devices() {
        let server = MockServer::start().await;
        mount_site_discovery(&server).await;

        Mock::given(method("GET"))
            .and(path_regex(r"/proxy/network/integration/v1/sites/.*/devices"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "offset": 0, "limit": 200, "count": 2, "totalCount": 2,
                "data": [
                    {"macAddress": "aa:bb:cc:dd:06:43", "ipAddress": "198.51.100.1", "name": "UCG Ultra", "model": "UCG Ultra", "state": "ONLINE", "firmwareVersion": "5.0.12"},
                    {"macAddress": "aa:bb:cc:dd:b8:00", "ipAddress": "198.51.100.190", "name": "U6-Lite", "model": "U6 Lite", "state": "ONLINE", "firmwareVersion": "6.7.41"}
                ]
            })))
            .mount(&server)
            .await;

        let mut client = mock_client(&server).await;
        let devices = client.list_devices().await.unwrap();
        assert_eq!(devices.len(), 2);
        assert_eq!(devices[0].name.as_deref(), Some("UCG Ultra"));
        assert_eq!(devices[1].firmware_version.as_deref(), Some("6.7.41"));
    }

    #[tokio::test]
    async fn restart_device_sends_correct_command() {
        let server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/proxy/network/api/s/default/cmd/devmgr"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": []
            })))
            .expect(1)
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        client.restart_device("aa:bb:cc:dd:ee:ff").await.unwrap();
    }

    #[tokio::test]
    async fn power_cycle_port_sends_correct_command() {
        let server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/proxy/network/api/s/default/cmd/devmgr"))
            .and(body_json(serde_json::json!({
                "cmd": "power-cycle",
                "mac": "aa:bb:cc:dd:ee:ff",
                "port_idx": 5
            })))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": []
            })))
            .expect(1)
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        client
            .power_cycle_port("AA-BB-CC-DD-EE-FF", 5)
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn upgrade_device_sends_correct_command() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/proxy/network/api/s/default/cmd/devmgr"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"meta": {"rc": "ok"}, "data": []})),
            )
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        client.upgrade_device("aa:bb:cc:dd:ee:ff").await.unwrap();
    }

    #[tokio::test]
    async fn locate_device_enable() {
        let server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/proxy/network/api/s/default/cmd/devmgr"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": []
            })))
            .expect(1)
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        client
            .locate_device("aa:bb:cc:dd:ee:ff", true)
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn locate_device_disable() {
        let server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/proxy/network/api/s/default/cmd/devmgr"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": []
            })))
            .expect(1)
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        client
            .locate_device("aa:bb:cc:dd:ee:ff", false)
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn list_networks_returns_networks() {
        let server = MockServer::start().await;
        mount_site_discovery(&server).await;

        Mock::given(method("GET"))
            .and(path_regex(
                r"/proxy/network/integration/v1/sites/.*/networks",
            ))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "offset": 0, "limit": 200, "count": 3, "totalCount": 3,
                "data": [
                    {"name": "Default", "enabled": true, "vlanId": 1, "default": true},
                    {"name": "IoT", "enabled": true, "vlanId": 20, "default": false},
                    {"name": "Guest", "enabled": false, "vlanId": 10, "default": false}
                ]
            })))
            .mount(&server)
            .await;

        let mut client = mock_client(&server).await;
        let networks = client.list_networks().await.unwrap();
        assert_eq!(networks.len(), 3);
        assert_eq!(networks[0].name.as_deref(), Some("Default"));
        assert!(networks[0].default);
        assert_eq!(networks[1].vlan_id, Some(20));
        assert!(!networks[2].enabled);
    }

    #[tokio::test]
    async fn get_health_returns_subsystems() {
        let server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/health"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [
                    {"subsystem": "wan", "status": "ok", "wan_ip": "203.0.113.156", "isp_name": "ExampleISP"},
                    {"subsystem": "wlan", "status": "ok", "num_ap": 3, "num_sta": 15},
                    {"subsystem": "lan", "status": "ok", "num_sw": 4, "num_sta": 20}
                ]
            })))
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        let health = client.get_health().await.unwrap();
        assert_eq!(health.len(), 3);
        assert_eq!(health[0].wan_ip.as_deref(), Some("203.0.113.156"));
        assert_eq!(health[1].num_ap, Some(3));
        assert_eq!(health[2].num_switches, Some(4));
    }

    #[tokio::test]
    async fn get_sysinfo_returns_info() {
        let server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/sysinfo"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [{
                    "hostname": "UCG-Ultra",
                    "version": "10.1.85",
                    "timezone": "Europe/Amsterdam",
                    "uptime": 1737960
                }]
            })))
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        let info = client.get_sysinfo().await.unwrap();
        assert_eq!(info.hostname.as_deref(), Some("UCG-Ultra"));
        assert_eq!(info.version.as_deref(), Some("10.1.85"));
        assert_eq!(info.uptime, Some(1737960));
    }

    #[tokio::test]
    async fn get_sysinfo_empty_data() {
        let server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/sysinfo"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": []
            })))
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        let err = client.get_sysinfo().await.unwrap_err();
        assert!(err.to_string().contains("No sysinfo returned"));
    }

    #[tokio::test]
    async fn list_all_device_ports_returns_every_device() {
        let server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/device"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [
                    {"mac": "aa:bb:cc:dd:ee:ff", "name": "SwitchA",
                     "port_table": [{"port_idx": 1, "port_poe": true}]},
                    {"mac": "11:22:33:44:55:66", "name": "SwitchB",
                     "port_table": [{"port_idx": 1}, {"port_idx": 2}]}
                ]
            })))
            .expect(1)
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        let devices = client.list_all_device_ports().await.unwrap();
        assert_eq!(devices.len(), 2);
        assert_eq!(devices[1].port_table.len(), 2);
    }
}

// --- Error handling tests ---

mod error_handling {
    use super::*;

    #[tokio::test]
    async fn api_returns_401_unauthorized() {
        let server = MockServer::start().await;
        mount_site_discovery(&server).await;

        Mock::given(method("GET"))
            .and(path_regex(
                r"/proxy/network/integration/v1/sites/.*/clients",
            ))
            .respond_with(ResponseTemplate::new(401).set_body_string("Unauthorized"))
            .mount(&server)
            .await;

        let mut client = mock_client(&server).await;
        let err = client.list_clients().await.unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("Authentication error:"));
        assert!(msg.contains("Hint:"));
    }

    #[tokio::test]
    async fn api_returns_500_server_error() {
        let server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/health"))
            .respond_with(ResponseTemplate::new(500).set_body_string("Internal Server Error"))
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        let err = client.get_health().await.unwrap_err();
        assert!(err.to_string().contains("API error (500)"));
    }

    #[tokio::test]
    async fn legacy_api_returns_error_rc() {
        let server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/health"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "error", "msg": "api.err.LoginRequired"},
                "data": []
            })))
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        let err = client.get_health().await.unwrap_err();
        assert!(err.to_string().contains("api.err.LoginRequired"));
    }

    #[tokio::test]
    async fn legacy_api_error_without_message() {
        let server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/health"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "error"},
                "data": []
            })))
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        let err = client.get_health().await.unwrap_err();
        assert!(err.to_string().contains("unknown error"));
    }

    #[tokio::test]
    async fn no_sites_found() {
        let server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/proxy/network/integration/v1/sites"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "offset": 0, "limit": 25, "count": 0, "totalCount": 0,
                "data": []
            })))
            .mount(&server)
            .await;

        Mock::given(method("GET"))
            .and(path_regex(
                r"/proxy/network/integration/v1/sites/.*/clients",
            ))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "offset": 0, "limit": 200, "count": 0, "totalCount": 0, "data": []
            })))
            .mount(&server)
            .await;

        let mut client = mock_client(&server).await;
        let err = client.list_clients().await.unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains("No sites found") && msg.contains("API key"));
    }

    #[tokio::test]
    async fn post_command_returns_error() {
        let server = MockServer::start().await;

        Mock::given(method("POST"))
            .and(path("/proxy/network/api/s/default/cmd/stamgr"))
            .respond_with(ResponseTemplate::new(403).set_body_string("Forbidden"))
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        let err = client.block_client("aa:bb:cc:dd:ee:ff").await.unwrap_err();
        assert!(err.to_string().contains("Authentication error:"));
    }

    #[tokio::test]
    async fn list_events_returns_events() {
        let server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/event"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [
                    {"key": "EVT_WU_Connected", "msg": "User connected", "subsystem": "wlan", "time": 1700000000, "datetime": "2024-01-01T00:00:00Z"},
                    {"key": "EVT_LU_Disconnected", "msg": "User disconnected", "subsystem": "lan", "time": 1700000001}
                ]
            })))
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        let events = client.list_events(10).await.unwrap();
        assert_eq!(events.len(), 2);
        assert_eq!(events[0].key.as_deref(), Some("EVT_WU_Connected"));
        assert_eq!(events[1].subsystem.as_deref(), Some("lan"));
    }

    #[tokio::test]
    async fn list_clients_legacy_returns_clients() {
        let server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/sta"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [
                    {"_id": "c1", "mac": "aa:bb:cc:dd:ee:ff", "ip": "192.0.2.1", "name": "Desktop", "is_wired": true, "tx_bytes": 1000000, "rx_bytes": 2000000},
                    {"_id": "c2", "mac": "11:22:33:44:55:66", "ip": "192.0.2.2", "hostname": "phone", "is_wired": false, "tx_bytes": 500, "rx_bytes": 300}
                ]
            })))
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        let clients = client.list_clients_legacy().await.unwrap();
        assert_eq!(clients.len(), 2);
        assert_eq!(clients[0].tx_bytes, Some(1000000));
        assert_eq!(clients[1].display_name(), "phone");
    }

    #[tokio::test]
    async fn get_device_ports_finds_by_mac() {
        let server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/device"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [{
                    "mac": "aa:bb:cc:dd:06:43", "name": "USW-24-PoE",
                    "model": "USW-24-PoE",
                    "port_table": [
                        {"port_idx": 1, "name": "Port 1", "media": "GE", "up": true, "speed": 1000, "full_duplex": true, "poe_enable": true, "poe_power": 5.2, "port_poe": true, "tx_bytes": 123456, "rx_bytes": 654321},
                        {"port_idx": 2, "name": "Port 2", "media": "GE", "up": false, "speed": 0, "full_duplex": false, "poe_enable": false, "port_poe": true, "tx_bytes": 0, "rx_bytes": 0}
                    ]
                }]
            })))
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        let device = client.get_device_ports("aa:bb:cc:dd:06:43").await.unwrap();
        assert_eq!(device.port_table.len(), 2);
        assert!(device.port_table[0].up);
        assert!(!device.port_table[1].up);
        assert_eq!(device.port_table[0].poe_power, Some(5.2));
    }

    #[tokio::test]
    async fn get_device_ports_not_found() {
        let server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/device"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": []
            })))
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        let err = client
            .get_device_ports("00:00:00:00:00:00")
            .await
            .unwrap_err();
        assert!(err.to_string().contains("Not found"));
    }

    #[tokio::test]
    async fn list_clients_legacy_sorted_by_bandwidth_descending() {
        let server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/sta"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [
                    {"_id": "c1", "mac": "aa:bb:cc:dd:ee:01", "name": "Light", "is_wired": true, "tx_bytes": 100, "rx_bytes": 200},
                    {"_id": "c2", "mac": "aa:bb:cc:dd:ee:02", "name": "Heavy", "is_wired": true, "tx_bytes": 5000000, "rx_bytes": 10000000},
                    {"_id": "c3", "mac": "aa:bb:cc:dd:ee:03", "name": "Medium", "is_wired": false, "tx_bytes": 50000, "rx_bytes": 60000}
                ]
            })))
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        let mut clients = client.list_clients_legacy().await.unwrap();

        // Verify sorting matches what `clients top` does
        clients
            .sort_by_key(|c| std::cmp::Reverse(c.tx_bytes.unwrap_or(0) + c.rx_bytes.unwrap_or(0)));

        assert_eq!(clients[0].display_name(), "Heavy");
        assert_eq!(clients[1].display_name(), "Medium");
        assert_eq!(clients[2].display_name(), "Light");
    }

    #[tokio::test]
    async fn get_device_ports_field_values() {
        let server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/device"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [{
                    "mac": "aa:bb:cc:dd:ee:ff", "name": "TestSwitch",
                    "port_table": [
                        {"port_idx": 1, "name": "Uplink", "media": "GE", "up": true, "speed": 1000, "full_duplex": true, "poe_enable": true, "poe_power": 12.5, "port_poe": true, "tx_bytes": 999999, "rx_bytes": 888888},
                        {"port_idx": 2, "up": false, "port_poe": false},
                        {"port_idx": 3, "up": true, "speed": 100, "full_duplex": false, "poe_enable": false, "port_poe": true}
                    ]
                }]
            })))
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        let device = client.get_device_ports("aa:bb:cc:dd:ee:ff").await.unwrap();
        assert_eq!(device.name.as_deref(), Some("TestSwitch"));

        // Port 1: full data
        let p1 = &device.port_table[0];
        assert_eq!(p1.port_idx, Some(1));
        assert_eq!(p1.name.as_deref(), Some("Uplink"));
        assert!(p1.up);
        assert_eq!(p1.speed, Some(1000));
        assert!(p1.full_duplex);
        assert!(p1.poe_enable);
        assert_eq!(p1.poe_power, Some(12.5));
        assert_eq!(p1.tx_bytes, Some(999999));
        assert_eq!(p1.rx_bytes, Some(888888));

        // Port 2: minimal data, down
        let p2 = &device.port_table[1];
        assert!(!p2.up);
        assert!(p2.name.is_none());
        assert!(!p2.port_poe);

        // Port 3: up, half duplex, PoE-capable but disabled
        let p3 = &device.port_table[2];
        assert!(p3.up);
        assert_eq!(p3.speed, Some(100));
        assert!(!p3.full_duplex);
        assert!(!p3.poe_enable);
        assert!(p3.port_poe);
    }
}

// --- Command output tests ---
// These exercise the commands::* functions which format and print results

mod command_output {
    use super::*;
    use unifi_cli::output::OutputConfig;

    fn out_table() -> OutputConfig {
        OutputConfig::new(unifi_cli::output::OutputFormat::Text, false)
    }

    fn out_json() -> OutputConfig {
        OutputConfig::new(unifi_cli::output::OutputFormat::Json, false)
    }

    fn default_pagination() -> unifi_cli::commands::clients::Pagination {
        unifi_cli::commands::clients::Pagination {
            limit: 100,
            offset: 0,
            fields: None,
        }
    }

    fn default_devices_pagination() -> unifi_cli::commands::devices::Pagination {
        unifi_cli::commands::devices::Pagination {
            limit: 100,
            offset: 0,
            fields: None,
        }
    }

    fn default_events_pagination(limit: usize) -> unifi_cli::commands::events::Pagination {
        unifi_cli::commands::events::Pagination {
            limit,
            offset: 0,
            fields: None,
        }
    }

    // Helper: mount sites + both client endpoints.
    //
    // `clients list` joins the integration-API record to the live legacy record
    // so it can report SSID, network and the address the client actually holds.
    // Device1's live address deliberately differs from the integration API's
    // last-known value, and host2 has no live address at all.
    async fn mount_clients_list(server: &MockServer) {
        mount_site_discovery(server).await;
        Mock::given(method("GET"))
            .and(path_regex(r"/proxy/network/integration/v1/sites/.*/clients"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "offset": 0, "limit": 200, "count": 2, "totalCount": 2,
                "data": [
                    {"macAddress": "aa:bb:cc:dd:ee:ff", "ipAddress": "192.0.2.1", "name": "Device1", "type": "WIRED"},
                    {"macAddress": "11:22:33:44:55:66", "ipAddress": "192.0.2.2", "hostname": "host2", "type": "WIRELESS"}
                ]
            })))
            .mount(server)
            .await;

        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/sta"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [
                    {"_id": "1", "mac": "aa:bb:cc:dd:ee:ff", "ip": "192.0.2.99",
                     "is_wired": true, "network": "Default", "vlan": 1},
                    {"_id": "2", "mac": "11:22:33:44:55:66", "essid": "GuestNet",
                     "signal": -55, "uptime": 100, "network": "IoT", "vlan": 20}
                ]
            })))
            .mount(server)
            .await;
    }

    /// `clients list` also reads the live legacy view. Tests that only care about
    /// filtering can serve an empty one.
    async fn mount_empty_legacy_clients(server: &MockServer) {
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/sta"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"}, "data": []
            })))
            .mount(server)
            .await;
    }

    fn no_filter() -> unifi_cli::commands::clients::ListFilter {
        unifi_cli::commands::clients::ListFilter {
            wired: false,
            wireless: false,
            name: None,
        }
    }

    #[tokio::test]
    async fn clients_list_table() {
        let server = MockServer::start().await;
        mount_clients_list(&server).await;
        let mut client = mock_client(&server).await;
        unifi_cli::commands::clients::list(
            &mut client,
            out_table(),
            no_filter(),
            None,
            default_pagination(),
        )
        .await
        .unwrap();
    }

    #[tokio::test]
    async fn clients_list_json() {
        let server = MockServer::start().await;
        mount_clients_list(&server).await;
        let mut client = mock_client(&server).await;
        unifi_cli::commands::clients::list(
            &mut client,
            out_json(),
            no_filter(),
            None,
            default_pagination(),
        )
        .await
        .unwrap();
    }

    #[tokio::test]
    async fn clients_show_wired_table() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/sta"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [{
                    "_id": "abc", "mac": "aa:bb:cc:dd:ee:ff", "ip": "192.0.2.1",
                    "name": "WiredDevice", "is_wired": true, "uptime": 86400,
                    "tx_bytes": 1048576, "rx_bytes": 2097152
                }]
            })))
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        unifi_cli::commands::clients::show(&client, "aa:bb:cc:dd:ee:ff", out_table())
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn clients_show_wireless_table() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/sta"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [{
                    "_id": "def", "mac": "11:22:33:44:55:66", "ip": "192.0.2.2",
                    "name": "WirelessDevice", "is_wired": false, "uptime": 3600,
                    "tx_bytes": 512000, "rx_bytes": 1024000,
                    "signal": -55, "essid": "GuestNet", "ap_mac": "aa:bb:cc:dd:b8:00"
                }]
            })))
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        unifi_cli::commands::clients::show(&client, "11:22:33:44:55:66", out_table())
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn clients_show_json() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/sta"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [{
                    "_id": "abc", "mac": "aa:bb:cc:dd:ee:ff", "ip": "192.0.2.1",
                    "name": "Device", "is_wired": true
                }]
            })))
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        unifi_cli::commands::clients::show(&client, "aa:bb:cc:dd:ee:ff", out_json())
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn clients_set_fixed_ip_output() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/sta"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [{"_id": "c1", "mac": "aa:bb:cc:dd:ee:ff"}]
            })))
            .mount(&server)
            .await;
        Mock::given(method("PUT"))
            .and(path("/proxy/network/api/s/default/rest/user/c1"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"meta": {"rc": "ok"}, "data": [{}]})),
            )
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        unifi_cli::commands::clients::set_fixed_ip(
            &client,
            "aa:bb:cc:dd:ee:ff",
            "192.0.2.50",
            None,
            out_table(),
        )
        .await
        .unwrap();
    }

    #[tokio::test]
    async fn clients_set_fixed_ip_with_name_output() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/sta"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [{"_id": "c1", "mac": "aa:bb:cc:dd:ee:ff"}]
            })))
            .mount(&server)
            .await;
        Mock::given(method("PUT"))
            .and(path("/proxy/network/api/s/default/rest/user/c1"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"meta": {"rc": "ok"}, "data": [{}]})),
            )
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        unifi_cli::commands::clients::set_fixed_ip(
            &client,
            "aa:bb:cc:dd:ee:ff",
            "192.0.2.50",
            Some("MyDevice"),
            out_table(),
        )
        .await
        .unwrap();
    }

    #[tokio::test]
    async fn clients_block_output() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/proxy/network/api/s/default/cmd/stamgr"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"meta": {"rc": "ok"}, "data": []})),
            )
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        unifi_cli::commands::clients::block(&client, "aa:bb:cc:dd:ee:ff", out_table())
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn clients_unblock_output() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/proxy/network/api/s/default/cmd/stamgr"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"meta": {"rc": "ok"}, "data": []})),
            )
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        unifi_cli::commands::clients::unblock(&client, "aa:bb:cc:dd:ee:ff", out_table())
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn clients_kick_output() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/proxy/network/api/s/default/cmd/stamgr"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"meta": {"rc": "ok"}, "data": []})),
            )
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        unifi_cli::commands::clients::kick(&client, "aa:bb:cc:dd:ee:ff", out_table())
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn devices_list_table() {
        let server = MockServer::start().await;
        mount_site_discovery(&server).await;
        Mock::given(method("GET"))
            .and(path_regex(r"/proxy/network/integration/v1/sites/.*/devices"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "offset": 0, "limit": 200, "count": 1, "totalCount": 1,
                "data": [{"macAddress": "aa:bb:cc:dd:06:43", "ipAddress": "198.51.100.1", "name": "UCG Ultra", "model": "UCG Ultra", "state": "ONLINE", "firmwareVersion": "5.0.12"}]
            })))
            .mount(&server)
            .await;

        let mut client = mock_client(&server).await;
        unifi_cli::commands::devices::list(
            &mut client,
            out_table(),
            None,
            default_devices_pagination(),
        )
        .await
        .unwrap();
    }

    #[tokio::test]
    async fn devices_list_json() {
        let server = MockServer::start().await;
        mount_site_discovery(&server).await;
        Mock::given(method("GET"))
            .and(path_regex(r"/proxy/network/integration/v1/sites/.*/devices"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "offset": 0, "limit": 200, "count": 1, "totalCount": 1,
                "data": [{"macAddress": "aa:bb:cc:dd:06:43", "name": "UCG Ultra", "model": "UCG Ultra", "state": "ONLINE", "firmwareVersion": "5.0.12"}]
            })))
            .mount(&server)
            .await;

        let mut client = mock_client(&server).await;
        unifi_cli::commands::devices::list(
            &mut client,
            out_json(),
            None,
            default_devices_pagination(),
        )
        .await
        .unwrap();
    }

    #[tokio::test]
    async fn devices_restart_output() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/proxy/network/api/s/default/cmd/devmgr"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"meta": {"rc": "ok"}, "data": []})),
            )
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        unifi_cli::commands::devices::restart(&client, "aa:bb:cc:dd:ee:ff", out_table())
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn devices_locate_on_output() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/proxy/network/api/s/default/cmd/devmgr"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"meta": {"rc": "ok"}, "data": []})),
            )
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        unifi_cli::commands::devices::locate(&client, "aa:bb:cc:dd:ee:ff", false, out_table())
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn devices_locate_off_output() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/proxy/network/api/s/default/cmd/devmgr"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"meta": {"rc": "ok"}, "data": []})),
            )
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        unifi_cli::commands::devices::locate(&client, "aa:bb:cc:dd:ee:ff", true, out_table())
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn networks_list_table() {
        let server = MockServer::start().await;
        mount_site_discovery(&server).await;
        Mock::given(method("GET"))
            .and(path_regex(
                r"/proxy/network/integration/v1/sites/.*/networks",
            ))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "offset": 0, "limit": 200, "count": 2, "totalCount": 2,
                "data": [
                    {"name": "Default", "enabled": true, "vlanId": 1, "default": true},
                    {"name": "IoT", "enabled": true, "vlanId": 20, "default": false}
                ]
            })))
            .mount(&server)
            .await;

        let mut client = mock_client(&server).await;
        unifi_cli::commands::networks::list(&mut client, out_table())
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn networks_list_json() {
        let server = MockServer::start().await;
        mount_site_discovery(&server).await;
        Mock::given(method("GET"))
            .and(path_regex(
                r"/proxy/network/integration/v1/sites/.*/networks",
            ))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "offset": 0, "limit": 200, "count": 2, "totalCount": 2,
                "data": [
                    {"name": "Default", "enabled": true, "vlanId": 1, "default": true},
                    {"name": "IoT", "enabled": true, "vlanId": 20, "default": false}
                ]
            })))
            .mount(&server)
            .await;

        let mut client = mock_client(&server).await;
        unifi_cli::commands::networks::list(&mut client, out_json())
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn system_health_table() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/health"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [
                    {"subsystem": "wan", "status": "ok", "wan_ip": "203.0.113.4", "isp_name": "ISP"},
                    {"subsystem": "wlan", "status": "ok", "num_ap": 2, "num_sta": 10},
                    {"subsystem": "lan", "status": "ok", "num_sw": 3, "num_sta": 5},
                    {"subsystem": "vpn", "status": "unknown"}
                ]
            })))
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        unifi_cli::commands::system::health(&client, out_table())
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn system_health_json() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/health"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [
                    {"subsystem": "wan", "status": "ok", "wan_ip": "203.0.113.4", "isp_name": "ISP"}
                ]
            })))
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        unifi_cli::commands::system::health(&client, out_json())
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn system_info_table() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/sysinfo"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [{"hostname": "UCG-Ultra", "version": "10.1.85", "timezone": "Europe/Amsterdam", "uptime": 1737960}]
            })))
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        unifi_cli::commands::system::info(&client, out_table())
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn system_info_json() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/sysinfo"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [{"hostname": "UCG-Ultra", "version": "10.1.85", "timezone": "Europe/Amsterdam", "uptime": 1737960}]
            })))
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        unifi_cli::commands::system::info(&client, out_json())
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn system_info_partial_fields() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/sysinfo"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [{"hostname": "UCG-Ultra"}]
            })))
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        unifi_cli::commands::system::info(&client, out_table())
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn devices_show_table() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/device"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [{
                    "mac": "aa:bb:cc:dd:06:43", "ip": "198.51.100.1",
                    "name": "UCG Ultra", "model": "UCG Ultra",
                    "state": 1, "version": "5.0.12", "uptime": 86400, "num_sta": 42
                }]
            })))
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        unifi_cli::commands::devices::show(&client, "aa:bb:cc:dd:06:43", out_table())
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn devices_show_json() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/device"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [{
                    "mac": "aa:bb:cc:dd:06:43", "ip": "198.51.100.1",
                    "name": "UCG Ultra", "model": "UCG Ultra",
                    "state": 1, "version": "5.0.12"
                }]
            })))
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        unifi_cli::commands::devices::show(&client, "aa:bb:cc:dd:06:43", out_json())
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn devices_show_not_found() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/device"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": []
            })))
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        let err = unifi_cli::commands::devices::show(&client, "00:00:00:00:00:00", out_table())
            .await
            .unwrap_err();
        assert!(err.to_string().contains("Not found"));
    }

    // --- Filter integration tests ---
    // apply_filter is private, so we test filtering through the list command

    #[tokio::test]
    async fn clients_list_wired_filter() {
        let server = MockServer::start().await;
        mount_site_discovery(&server).await;
        mount_empty_legacy_clients(&server).await;
        Mock::given(method("GET"))
            .and(path_regex(
                r"/proxy/network/integration/v1/sites/.*/clients",
            ))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "offset": 0, "limit": 200, "count": 3, "totalCount": 3,
                "data": [
                    {"macAddress": "aa:bb:cc:dd:ee:01", "name": "WiredDevice", "type": "WIRED"},
                    {"macAddress": "aa:bb:cc:dd:ee:02", "name": "WirelessDevice", "type": "WIRELESS"},
                    {"macAddress": "aa:bb:cc:dd:ee:03", "name": "AnotherWired", "type": "WIRED"}
                ]
            })))
            .mount(&server)
            .await;

        let mut client = mock_client(&server).await;
        let filter = unifi_cli::commands::clients::ListFilter {
            wired: true,
            wireless: false,
            name: None,
        };
        // Should succeed (filter happens internally, we verify no error)
        unifi_cli::commands::clients::list(
            &mut client,
            out_json(),
            filter,
            None,
            default_pagination(),
        )
        .await
        .unwrap();
    }

    #[tokio::test]
    async fn clients_list_wireless_filter() {
        let server = MockServer::start().await;
        mount_site_discovery(&server).await;
        mount_empty_legacy_clients(&server).await;
        Mock::given(method("GET"))
            .and(path_regex(
                r"/proxy/network/integration/v1/sites/.*/clients",
            ))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "offset": 0, "limit": 200, "count": 2, "totalCount": 2,
                "data": [
                    {"macAddress": "aa:bb:cc:dd:ee:01", "name": "WiredDevice", "type": "WIRED"},
                    {"macAddress": "aa:bb:cc:dd:ee:02", "name": "WirelessDevice", "type": "WIRELESS"}
                ]
            })))
            .mount(&server)
            .await;

        let mut client = mock_client(&server).await;
        let filter = unifi_cli::commands::clients::ListFilter {
            wired: false,
            wireless: true,
            name: None,
        };
        unifi_cli::commands::clients::list(
            &mut client,
            out_json(),
            filter,
            None,
            default_pagination(),
        )
        .await
        .unwrap();
    }

    #[tokio::test]
    async fn clients_list_name_filter() {
        let server = MockServer::start().await;
        mount_site_discovery(&server).await;
        mount_empty_legacy_clients(&server).await;
        Mock::given(method("GET"))
            .and(path_regex(
                r"/proxy/network/integration/v1/sites/.*/clients",
            ))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "offset": 0, "limit": 200, "count": 3, "totalCount": 3,
                "data": [
                    {"macAddress": "aa:bb:cc:dd:ee:01", "name": "iPhone", "type": "WIRELESS"},
                    {"macAddress": "aa:bb:cc:dd:ee:02", "name": "Desktop", "type": "WIRED"},
                    {"macAddress": "aa:bb:cc:dd:ee:03", "name": "iPad", "type": "WIRELESS"}
                ]
            })))
            .mount(&server)
            .await;

        let mut client = mock_client(&server).await;
        let filter = unifi_cli::commands::clients::ListFilter {
            wired: false,
            wireless: false,
            name: Some("phone".into()),
        };
        unifi_cli::commands::clients::list(
            &mut client,
            out_json(),
            filter,
            None,
            default_pagination(),
        )
        .await
        .unwrap();
    }

    // --- Events ---

    #[tokio::test]
    async fn events_list_table() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/event"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [
                    {"key": "EVT_WU_Connected", "msg": "User[aa:bb:cc:dd:ee:ff] has connected", "subsystem": "wlan", "datetime": "2024-01-15T10:30:00Z"},
                    {"key": "EVT_SW_PoeOverload", "msg": "PoE overload on port 5", "subsystem": "lan", "datetime": "2024-01-15T10:29:00Z"}
                ]
            })))
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        unifi_cli::commands::events::list(&client, out_table(), default_events_pagination(10))
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn events_list_json() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/event"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [
                    {"key": "EVT_WU_Connected", "msg": "User connected", "subsystem": "wlan", "time": 1700000000}
                ]
            })))
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        unifi_cli::commands::events::list(&client, out_json(), default_events_pagination(5))
            .await
            .unwrap();
    }

    // --- Clients top ---

    #[tokio::test]
    async fn clients_top_table() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/sta"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [
                    {"_id": "c1", "mac": "aa:bb:cc:dd:ee:01", "ip": "192.0.2.1", "name": "Heavy User", "is_wired": true, "tx_bytes": 5000000000_u64, "rx_bytes": 10000000000_u64},
                    {"_id": "c2", "mac": "aa:bb:cc:dd:ee:02", "ip": "192.0.2.2", "name": "Light User", "is_wired": false, "tx_bytes": 1000, "rx_bytes": 2000},
                    {"_id": "c3", "mac": "aa:bb:cc:dd:ee:03", "ip": "192.0.2.3", "hostname": "medium-host", "is_wired": true, "tx_bytes": 500000, "rx_bytes": 600000}
                ]
            })))
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        unifi_cli::commands::clients::top(&client, out_table(), 2)
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn clients_top_json() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/sta"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [
                    {"_id": "c1", "mac": "aa:bb:cc:dd:ee:01", "ip": "192.0.2.1", "name": "User1", "is_wired": true, "tx_bytes": 100, "rx_bytes": 200}
                ]
            })))
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        unifi_cli::commands::clients::top(&client, out_json(), 10)
            .await
            .unwrap();
    }

    // --- Devices ports ---

    #[tokio::test]
    async fn devices_ports_table() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/device"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [{
                    "mac": "aa:bb:cc:dd:06:43", "name": "USW-24-PoE", "model": "USW-24-PoE",
                    "port_table": [
                        {"port_idx": 1, "name": "Port 1", "media": "GE", "up": true, "speed": 1000, "full_duplex": true, "poe_enable": true, "poe_power": 5.2, "port_poe": true, "tx_bytes": 123456789, "rx_bytes": 987654321},
                        {"port_idx": 2, "name": "Port 2", "media": "GE", "up": true, "speed": 100, "full_duplex": false, "poe_enable": false, "port_poe": true, "tx_bytes": 1000, "rx_bytes": 2000},
                        {"port_idx": 3, "name": "Port 3", "media": "GE", "up": false, "poe_enable": false, "port_poe": false}
                    ]
                }]
            })))
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        unifi_cli::commands::devices::ports(&client, "aa:bb:cc:dd:06:43", out_table())
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn devices_ports_json() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/device"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [{
                    "mac": "aa:bb:cc:dd:06:43", "name": "USW-Lite-8",
                    "port_table": [
                        {"port_idx": 1, "name": "Port 1", "media": "GE", "up": true, "speed": 1000, "full_duplex": true, "poe_enable": true, "poe_power": 3.8, "port_poe": true, "tx_bytes": 100, "rx_bytes": 200}
                    ]
                }]
            })))
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        unifi_cli::commands::devices::ports(&client, "aa:bb:cc:dd:06:43", out_json())
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn devices_ports_empty_port_table() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/device"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [{
                    "mac": "aa:bb:cc:dd:ee:ff", "name": "UAP-AC-Pro",
                    "port_table": []
                }]
            })))
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        unifi_cli::commands::devices::ports(&client, "aa:bb:cc:dd:ee:ff", out_table())
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn devices_upgrade_output() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/proxy/network/api/s/default/cmd/devmgr"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"meta": {"rc": "ok"}, "data": []})),
            )
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        unifi_cli::commands::devices::upgrade(&client, "aa:bb:cc:dd:ee:ff", out_table())
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn devices_upgrade_json() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/proxy/network/api/s/default/cmd/devmgr"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"meta": {"rc": "ok"}, "data": []})),
            )
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        unifi_cli::commands::devices::upgrade(&client, "aa:bb:cc:dd:ee:ff", out_json())
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn devices_ports_not_found() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/device"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": []
            })))
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        let err = unifi_cli::commands::devices::ports(&client, "00:00:00:00:00:00", out_table())
            .await
            .unwrap_err();
        assert!(err.to_string().contains("Not found"));
    }

    // `devices::ports` used to derive its own `name -> model -> "Device"`
    // device-label fallback; routing it through the shared `collect_rows`
    // silently changed the fallback to "-" for a device with neither `name`
    // nor `model`, and nothing caught it. Drives the real binary (JSON is
    // easiest to assert on) so the regression is locked in at the command
    // level, not just in the `collect_rows_with_fallback` unit test in
    // `src/commands/ports.rs`.
    #[tokio::test]
    async fn devices_ports_falls_back_to_device_label_when_name_and_model_absent() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/device"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [{
                    "mac": "aa:bb:cc:dd:ee:ff",
                    "port_table": [{"port_idx": 1}]
                }]
            })))
            .mount(&server)
            .await;

        let output = std::process::Command::new(env!("CARGO_BIN_EXE_unifi"))
            .args([
                "--host",
                &server.uri(),
                "--api-key",
                "test-key",
                "devices",
                "ports",
                "aa:bb:cc:dd:ee:ff",
                "-o",
                "json",
            ])
            .output()
            .expect("failed to run the unifi binary");
        assert!(
            output.status.success(),
            "devices ports failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );

        let body: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
        let items = body
            .as_array()
            .expect("devices ports must emit a bare JSON array");
        assert_eq!(
            items[0]["device_name"], "Device",
            "devices ports must keep its historical \"Device\" fallback, not \"-\": {items:?}"
        );
    }

    // --- Ports show (single-port detail) ---

    #[tokio::test]
    async fn ports_show_table() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/device"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [{
                    "mac": "aa:bb:cc:dd:06:43", "name": "USW-24-PoE",
                    "port_table": [
                        {"port_idx": 1, "name": "Port 1", "media": "GE", "up": true},
                        {
                            "port_idx": 5, "name": "Port 5", "media": "GE", "up": true,
                            "speed": 1000, "full_duplex": true, "autoneg": true, "enable": true,
                            "is_uplink": false, "stp_state": "forwarding",
                            "port_poe": true, "poe_enable": true, "poe_mode": "auto",
                            "poe_class": "4", "poe_power": 5.2, "poe_voltage": 53.5,
                            "poe_current": 120.3, "poe_good": true,
                            "last_connection": {"mac": "aabbccddeeff", "connected": true},
                            "tx_bytes": 100, "rx_bytes": 200, "tx_errors": 0, "rx_errors": 2
                        }
                    ]
                }]
            })))
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        unifi_cli::commands::ports::show(&client, "aa:bb:cc:dd:06:43", 5, out_table())
            .await
            .unwrap();
    }

    // `ports_show_table` above only smoke-tests that the text branch does not
    // panic. The text branch carries real formatting logic (speed_cell,
    // poe_cell, voltage/current, the attached MAC), so it also gets a test that
    // spawns the real binary and asserts on the rendered text.
    #[tokio::test]
    async fn ports_show_text_output_renders_expected_fields() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/device"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [{
                    "mac": "aa:bb:cc:dd:06:43", "name": "USW-24-PoE",
                    "port_table": [{
                        "port_idx": 5, "name": "Port 5", "media": "GE", "up": true,
                        "speed": 1000, "full_duplex": true,
                        "port_poe": true, "poe_enable": true, "poe_mode": "auto",
                        "poe_class": "4", "poe_power": 5.2, "poe_voltage": 53.5,
                        "poe_current": 120.3,
                        "last_connection": {"mac": "aabbccddeeff", "connected": true}
                    }]
                }]
            })))
            .mount(&server)
            .await;

        let output = std::process::Command::new(env!("CARGO_BIN_EXE_unifi"))
            .args([
                "--host",
                &server.uri(),
                "--api-key",
                "test-key",
                "ports",
                "show",
                "aa:bb:cc:dd:06:43",
                "5",
                "--output",
                "text",
            ])
            .output()
            .expect("failed to run the unifi binary");
        assert!(
            output.status.success(),
            "ports show failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );

        let text = String::from_utf8_lossy(&output.stdout);
        assert!(
            text.contains("Port 5 on USW-24-PoE (aa:bb:cc:dd:06:43)"),
            "title line: {text}"
        );
        assert!(text.contains("Port 5"), "port name: {text}");
        assert!(text.contains("1000FD"), "speed+duplex formatting: {text}");
        assert!(text.contains("GE"), "media: {text}");
        assert!(text.contains("5.2W"), "PoE wattage: {text}");
        assert!(text.contains("auto"), "PoE mode: {text}");
        assert!(text.contains("53.50 V"), "PoE voltage: {text}");
        assert!(text.contains("120.30 mA"), "PoE current: {text}");
        assert!(text.contains("aa:bb:cc:dd:ee:ff"), "attached MAC: {text}");
    }

    // Drives the real `unifi` binary so the JSON this command actually prints
    // can be inspected, and cross-checks it against what `unifi schema`
    // publishes for "ports show": the two are supposed to be the same
    // contract, and nothing else in this suite would catch them drifting
    // apart.
    #[tokio::test]
    async fn ports_show_json_matches_schema_output_fields() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/device"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [{
                    "mac": "aa:bb:cc:dd:06:43", "name": "USW-24-PoE",
                    "port_table": [{
                        "port_idx": 5, "name": "Port 5", "media": "GE", "up": true,
                        "speed": 1000, "full_duplex": true, "autoneg": true, "enable": true,
                        "is_uplink": false, "stp_state": "forwarding",
                        "port_poe": true, "poe_enable": true, "poe_mode": "auto",
                        "poe_class": "4", "poe_power": 5.2, "poe_voltage": 53.5,
                        "poe_current": 120.3, "poe_good": true,
                        "last_connection": {"mac": "aabbccddeeff", "connected": true},
                        "tx_bytes": 100, "rx_bytes": 200, "tx_errors": 0, "rx_errors": 2
                    }]
                }]
            })))
            .mount(&server)
            .await;

        let output = std::process::Command::new(env!("CARGO_BIN_EXE_unifi"))
            .args([
                "--host",
                &server.uri(),
                "--api-key",
                "test-key",
                "ports",
                "show",
                "aa:bb:cc:dd:06:43",
                "5",
                "--output",
                "json",
            ])
            .output()
            .expect("failed to run the unifi binary");
        assert!(
            output.status.success(),
            "ports show failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );

        let body: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap_or_else(|e| {
            panic!(
                "stdout was not valid JSON ({e}): {}",
                String::from_utf8_lossy(&output.stdout)
            )
        });
        let obj = body
            .as_object()
            .expect("ports show must emit a JSON object");

        // Values that were previously fetched and thrown away.
        assert_eq!(obj["device_mac"], "aa:bb:cc:dd:06:43");
        assert_eq!(obj["port_idx"], 5);
        assert_eq!(obj["poe_mode"], "auto");
        assert_eq!(obj["poe_class"], "4");
        assert_eq!(obj["poe_voltage"], 53.5);
        assert_eq!(obj["poe_current"], 120.3);
        assert_eq!(obj["poe_good"], true);
        assert_eq!(
            obj["attached_mac"], "aa:bb:cc:dd:ee:ff",
            "attached_mac must be read from last_connection.mac and formatted"
        );
        assert_eq!(obj["tx_errors"], 0);
        assert_eq!(obj["rx_errors"], 2);

        crate::assert_schema_matches("ports show", &body);
    }

    // `autoneg`/`enable`/`is_uplink`/`poe_good` are tri-state: a firmware that
    // omits the key must serialize as JSON null, not fall back to `false`,
    // since a missing key must not read as a confident "disabled". Likewise
    // `attached_mac` must be null when no device has ever linked to the port.
    #[tokio::test]
    async fn ports_show_omitted_tri_state_fields_serialize_as_null() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/device"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [{
                    "mac": "aa:bb:cc:dd:ee:ff", "name": "USW-Lite-8",
                    "port_table": [
                        {"port_idx": 3, "name": "Port 3", "media": "GE", "up": false}
                    ]
                }]
            })))
            .mount(&server)
            .await;

        let output = std::process::Command::new(env!("CARGO_BIN_EXE_unifi"))
            .args([
                "--host",
                &server.uri(),
                "--api-key",
                "test-key",
                "ports",
                "show",
                "aa:bb:cc:dd:ee:ff",
                "3",
                "--output",
                "json",
            ])
            .output()
            .expect("failed to run the unifi binary");
        assert!(output.status.success());

        let body: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
        for field in ["autoneg", "enable", "is_uplink", "poe_good", "attached_mac"] {
            assert!(
                body[field].is_null(),
                "{field} must be null when firmware omits it, not false: {body}"
            );
        }
    }

    // A `last_connection` the controller has marked `connected: false` is
    // history, not an attachment: the device may have been unplugged months
    // ago. Reporting it as attached would tell an operator a port is in use
    // moments before they cut its power, so `attached_mac` must be null and the
    // MAC must survive only as `attached_last_seen_mac`.
    #[tokio::test]
    async fn ports_show_reports_a_stale_last_connection_as_unattached() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/device"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [{
                    "mac": "aa:bb:cc:dd:06:43", "name": "USW-24-PoE",
                    "port_table": [{
                        "port_idx": 5, "name": "Port 5", "media": "GE", "up": false,
                        "port_poe": true, "poe_enable": true, "poe_mode": "auto",
                        "last_connection": {"mac": "aabbccddeeff", "connected": false}
                    }]
                }]
            })))
            .mount(&server)
            .await;

        let run = |format: &str| {
            std::process::Command::new(env!("CARGO_BIN_EXE_unifi"))
                .args([
                    "--host",
                    &server.uri(),
                    "--api-key",
                    "test-key",
                    "ports",
                    "show",
                    "aa:bb:cc:dd:06:43",
                    "5",
                    "--output",
                    format,
                ])
                .output()
                .expect("failed to run the unifi binary")
        };

        let json_out = run("json");
        assert!(
            json_out.status.success(),
            "ports show failed: {}",
            String::from_utf8_lossy(&json_out.stderr)
        );
        let body: serde_json::Value = serde_json::from_slice(&json_out.stdout).unwrap();
        assert!(
            body["attached_mac"].is_null(),
            "a stale last_connection must not be published as attached: {body}"
        );
        assert_eq!(
            body["attached_last_seen_mac"], "aa:bb:cc:dd:ee:ff",
            "the stale MAC must stay available as history: {body}"
        );
        assert_eq!(
            body["attached_connected"], false,
            "the controller's own flag must be reported as it stands: {body}"
        );

        let text_out = run("text");
        assert!(text_out.status.success());
        let text = String::from_utf8_lossy(&text_out.stdout);
        assert!(
            text.contains("- (last seen aa:bb:cc:dd:ee:ff)"),
            "the text branch must qualify a stale MAC rather than print it bare: {text}"
        );
    }

    // A firmware that reports `last_connection.mac` without a `connected` flag
    // has said nothing about the present, which is not the same fact as
    // "disconnected". It is still not grounds to claim an attachment, so
    // `attached_mac` stays null, but the tri-state `attached_connected` and the
    // text output both distinguish "not reported" from "gone".
    #[tokio::test]
    async fn ports_show_distinguishes_an_unreported_connection_from_a_stale_one() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/device"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [{
                    "mac": "aa:bb:cc:dd:06:43", "name": "USW-24-PoE",
                    "port_table": [{
                        "port_idx": 5, "name": "Port 5", "media": "GE", "up": true,
                        "last_connection": {"mac": "aabbccddeeff"}
                    }]
                }]
            })))
            .mount(&server)
            .await;

        let run = |format: &str| {
            std::process::Command::new(env!("CARGO_BIN_EXE_unifi"))
                .args([
                    "--host",
                    &server.uri(),
                    "--api-key",
                    "test-key",
                    "ports",
                    "show",
                    "aa:bb:cc:dd:06:43",
                    "5",
                    "--output",
                    format,
                ])
                .output()
                .expect("failed to run the unifi binary")
        };

        let json_out = run("json");
        assert!(json_out.status.success());
        let body: serde_json::Value = serde_json::from_slice(&json_out.stdout).unwrap();
        assert!(
            body["attached_mac"].is_null(),
            "an unreported connection must not be claimed as attached: {body}"
        );
        assert!(
            body["attached_connected"].is_null(),
            "a missing connected flag must stay null, not become false: {body}"
        );
        assert_eq!(body["attached_last_seen_mac"], "aa:bb:cc:dd:ee:ff");

        let text = String::from_utf8_lossy(&run("text").stdout).to_string();
        assert!(
            text.contains("unknown (last seen aa:bb:cc:dd:ee:ff)"),
            "the text branch must say the state is unknown, not that the device is gone: {text}"
        );
    }

    // Locates `unifi ports cycle <MAC> 99` uses the same `find_port` lookup;
    // a bogus port index must be reported as not-found (exit 4) rather than
    // firing a command at the controller for a port that does not exist.
    #[tokio::test]
    async fn ports_show_not_found() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/device"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [{
                    "mac": "aa:bb:cc:dd:ee:ff", "name": "USW-Lite-8",
                    "port_table": [{"port_idx": 1}]
                }]
            })))
            .mount(&server)
            .await;

        let output = std::process::Command::new(env!("CARGO_BIN_EXE_unifi"))
            .args([
                "--host",
                &server.uri(),
                "--api-key",
                "test-key",
                "ports",
                "show",
                "aa:bb:cc:dd:ee:ff",
                "99",
            ])
            .output()
            .expect("failed to run the unifi binary");

        assert_eq!(
            output.status.code(),
            Some(4),
            "a nonexistent port must exit 4 (not found), got {:?}\nstderr: {}",
            output.status.code(),
            String::from_utf8_lossy(&output.stderr)
        );
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(
            stderr.contains("Not found"),
            "stderr must explain the port was not found: {stderr}"
        );
    }

    // The row-count trailer must read "1 port" for a single row and "N ports"
    // otherwise. Spawns the real binary (rather than calling `render_text`
    // in-process) so this observes literal stderr text, the same surface an
    // operator actually reads.
    #[tokio::test]
    async fn ports_list_trailer_is_singular_for_exactly_one_row() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/device"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [{"mac": "aa:bb:cc:dd:ee:01", "name": "SwitchA",
                          "port_table": [{"port_idx": 1}]}]
            })))
            .mount(&server)
            .await;

        let output = std::process::Command::new(env!("CARGO_BIN_EXE_unifi"))
            .args([
                "--host",
                &server.uri(),
                "--api-key",
                "test-key",
                "ports",
                "list",
                "--output",
                "text",
            ])
            .output()
            .expect("failed to run the unifi binary");
        assert!(
            output.status.success(),
            "ports list failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(
            stderr.trim_end().ends_with("1 port"),
            "a single row must be reported as \"1 port\", not \"1 ports\": {stderr:?}"
        );
    }

    #[tokio::test]
    async fn ports_list_trailer_is_plural_for_multiple_rows() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/device"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [{"mac": "aa:bb:cc:dd:ee:01", "name": "SwitchA",
                          "port_table": [{"port_idx": 1}, {"port_idx": 2}]}]
            })))
            .mount(&server)
            .await;

        let output = std::process::Command::new(env!("CARGO_BIN_EXE_unifi"))
            .args([
                "--host",
                &server.uri(),
                "--api-key",
                "test-key",
                "ports",
                "list",
                "--output",
                "text",
            ])
            .output()
            .expect("failed to run the unifi binary");
        assert!(
            output.status.success(),
            "ports list failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(
            stderr.trim_end().ends_with("2 ports"),
            "two rows must be reported as \"2 ports\": {stderr:?}"
        );
    }

    // --- Ports list (top-level) ---
    //
    // Drives the real `unifi` binary against a wiremock server so the JSON
    // envelope it actually prints can be inspected. A regression that computed
    // `total` from the truncated page (instead of the full flattened result)
    // would let an agent mistake a partial page for a complete one, so this
    // must observe real stdout rather than call `commands::ports::list`
    // in-process and only check that it returns `Ok`.
    #[tokio::test]
    async fn ports_list_pagination_reports_full_total_and_truncated_items() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/device"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [
                    {"mac": "aa:bb:cc:dd:ee:01", "name": "SwitchA",
                     "port_table": [{"port_idx": 1}, {"port_idx": 2}]},
                    {"mac": "aa:bb:cc:dd:ee:02", "name": "SwitchB",
                     "port_table": [{"port_idx": 1}, {"port_idx": 2}, {"port_idx": 3}]}
                ]
            })))
            .mount(&server)
            .await;

        let output = std::process::Command::new(env!("CARGO_BIN_EXE_unifi"))
            .args([
                "--host",
                &server.uri(),
                "--api-key",
                "test-key",
                "ports",
                "list",
                "--output",
                "json",
                "--limit",
                "3",
                "--offset",
                "1",
            ])
            .output()
            .expect("failed to run the unifi binary");

        assert!(
            output.status.success(),
            "ports list failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );

        let body: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap_or_else(|e| {
            panic!(
                "stdout was not valid JSON ({e}): {}",
                String::from_utf8_lossy(&output.stdout)
            )
        });

        let items = body["items"]
            .as_array()
            .expect("envelope must have an items array");
        assert_eq!(
            items.len(),
            3,
            "the page must be truncated to the requested limit"
        );
        assert_eq!(
            body["total"], 5,
            "total must reflect every port across every device, not just this page"
        );
        assert_ne!(
            body["total"].as_u64().unwrap(),
            items.len() as u64,
            "an agent must be able to tell a truncated page from a complete result"
        );
        assert_eq!(body["limit"], 3);
        assert_eq!(body["offset"], 1);
    }

    // `render_text`'s Device column width used to be derived from whatever
    // page it was handed, which for `ports list` is the already-paginated
    // page. Two `--offset` pages of the same query could then render the
    // column at different widths. The device names below are chosen so the
    // longest one falls on the second page only; if the width regressed back
    // to being page-local, the two headers would render at different widths
    // and this comparison would fail.
    #[tokio::test]
    async fn ports_list_device_column_width_is_stable_across_pages() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/device"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [
                    {"mac": "aa:bb:cc:dd:ee:01", "name": "SwitchA",
                     "port_table": [{"port_idx": 1}, {"port_idx": 2}]},
                    {"mac": "aa:bb:cc:dd:ee:02", "name": "A-Very-Long-Switch-Name",
                     "port_table": [{"port_idx": 1}]}
                ]
            })))
            .mount(&server)
            .await;

        let run_text = |limit: &str, offset: &str| -> String {
            let output = std::process::Command::new(env!("CARGO_BIN_EXE_unifi"))
                .args([
                    "--host",
                    &server.uri(),
                    "--api-key",
                    "test-key",
                    "ports",
                    "list",
                    "--output",
                    "text",
                    "--limit",
                    limit,
                    "--offset",
                    offset,
                ])
                .output()
                .expect("failed to run the unifi binary");
            assert!(output.status.success());
            String::from_utf8_lossy(&output.stdout).into_owned()
        };

        // Page 1: only SwitchA's two ports (the long name lives on page 2).
        let page1 = run_text("2", "0");
        // Page 2: only the long-named device's one port.
        let page2 = run_text("1", "2");

        fn header(s: &str) -> &str {
            s.lines()
                .find(|l| l.contains("Device"))
                .expect("text output must have a header row containing \"Device\"")
        }
        assert_eq!(
            header(&page1),
            header(&page2),
            "the Device column width must come from the full result set, not the page, \
             so two --offset pages of the same query render an identical header:\n\
             page1: {page1}\npage2: {page2}"
        );
    }

    // `devices ports <MAC>` is documented as an alias for `ports list <MAC>`
    // that deliberately keeps the historical bare JSON array shape, while
    // `ports list` emits the paginated `{items,total,limit,offset}` envelope.
    // Wrapping `devices ports` in the envelope would break any consumer that
    // indexes the top level, which the design explicitly forbids.
    //
    // Nothing else in this suite would catch that regression: the in-process
    // `devices_ports_*` tests above only `.unwrap()`/`.unwrap_err()` and never
    // capture stdout, and `devices_ports_and_ports_list_are_the_same_command`
    // in `tests/cli_contract.rs` only asserts the exit code isn't a usage
    // error. So this spawns the real compiled binary against a wiremock
    // server (same pattern as `ports_list_pagination_reports_full_total_and_truncated_items`
    // above) and parses actual stdout as JSON to assert on shape.
    #[tokio::test]
    async fn devices_ports_bare_array_vs_ports_list_envelope() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/device"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [{
                    "mac": "aa:bb:cc:dd:06:43", "name": "USW-24-PoE",
                    "port_table": [
                        {"port_idx": 1, "name": "Port 1", "media": "GE", "up": true, "speed": 1000, "full_duplex": true, "poe_enable": true, "poe_power": 5.2, "port_poe": true, "tx_bytes": 123456789, "rx_bytes": 987654321},
                        {"port_idx": 2, "name": "Port 2", "media": "GE", "up": true, "speed": 100, "full_duplex": false, "poe_enable": false, "port_poe": true, "tx_bytes": 1000, "rx_bytes": 2000}
                    ]
                }]
            })))
            .mount(&server)
            .await;

        let run_json = |args: &[&str]| -> serde_json::Value {
            let output = std::process::Command::new(env!("CARGO_BIN_EXE_unifi"))
                .args(["--host", &server.uri(), "--api-key", "test-key"])
                .args(args)
                .output()
                .expect("failed to run the unifi binary");
            assert!(
                output.status.success(),
                "{args:?} failed: {}",
                String::from_utf8_lossy(&output.stderr)
            );
            serde_json::from_slice(&output.stdout).unwrap_or_else(|e| {
                panic!(
                    "{args:?} stdout was not valid JSON ({e}): {}",
                    String::from_utf8_lossy(&output.stdout)
                )
            })
        };

        let alias = run_json(&["devices", "ports", "aa:bb:cc:dd:06:43", "-o", "json"]);
        let canonical = run_json(&["ports", "list", "aa:bb:cc:dd:06:43", "-o", "json"]);

        // 1. `devices ports` must be a bare array, and rows must carry the
        //    device_mac/device_name fields shared with `ports list`.
        let alias_items = alias
            .as_array()
            .unwrap_or_else(|| panic!("devices ports must emit a bare JSON array, got: {alias}"));
        assert!(
            !alias_items.is_empty(),
            "expected at least one port row from devices ports"
        );
        let alias_row = alias_items[0]
            .as_object()
            .expect("devices ports row must be a JSON object");
        assert!(
            alias_row.contains_key("device_mac"),
            "devices ports row must carry device_mac: {alias_row:?}"
        );
        assert!(
            alias_row.contains_key("device_name"),
            "devices ports row must carry device_name: {alias_row:?}"
        );

        // 2. `ports list` must be the {items,total,limit,offset} envelope.
        assert!(
            canonical.is_object(),
            "ports list must emit an {{items,total,limit,offset}} envelope object, got: {canonical}"
        );
        let items = canonical["items"]
            .as_array()
            .expect("ports list envelope must have an items array");
        assert!(
            canonical.get("total").is_some(),
            "ports list envelope must have a total field"
        );
        assert!(
            canonical.get("limit").is_some(),
            "ports list envelope must have a limit field"
        );
        assert!(
            canonical.get("offset").is_some(),
            "ports list envelope must have an offset field"
        );
        assert!(
            !items.is_empty(),
            "expected at least one port row from ports list"
        );

        // 3. The two spellings must carry the same key set per row, locking
        //    in the shared-field-set property alongside the envelope split.
        let mut alias_keys: Vec<&str> = alias_row.keys().map(String::as_str).collect();
        alias_keys.sort_unstable();
        let mut canonical_keys: Vec<&str> = items[0]
            .as_object()
            .expect("ports list row must be a JSON object")
            .keys()
            .map(String::as_str)
            .collect();
        canonical_keys.sort_unstable();

        assert_eq!(
            alias_keys, canonical_keys,
            "devices ports and ports list must share the same per-row field set"
        );
    }

    // --- Ports find (reverse lookup) ---

    // A MAC identifier must resolve locally so the common scripted path stays
    // a single round trip; mounting `/stat/sta` with `.expect(0)` turns an
    // accidental client-list fetch into a test failure instead of a silent,
    // unnoticed second request. This also locks in connected-first sorting
    // and the exact `PORTS_FIND` field set end to end, through the real
    // binary and JSON output, not just the in-process helpers.
    #[tokio::test]
    async fn ports_find_by_mac_sorts_connected_first_and_skips_client_lookup() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/device"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [{
                    "mac": "aa:bb:cc:dd:06:43", "name": "USW-24-PoE",
                    "port_table": [
                        {"port_idx": 2, "last_connection": {"mac": "aa:bb:cc:dd:ee:10", "connected": false}},
                        {"port_idx": 7, "last_connection": {"mac": "aa:bb:cc:dd:ee:10", "connected": true}},
                        {"port_idx": 9, "last_connection": {"mac": "11:22:33:44:55:66", "connected": true}}
                    ]
                }]
            })))
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/sta"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"}, "data": []
            })))
            .expect(0)
            .mount(&server)
            .await;

        let output = std::process::Command::new(env!("CARGO_BIN_EXE_unifi"))
            .args([
                "--host",
                &server.uri(),
                "--api-key",
                "test-key",
                "ports",
                "find",
                "aa:bb:cc:dd:ee:10",
                "-o",
                "json",
            ])
            .output()
            .expect("failed to run the unifi binary");
        assert!(
            output.status.success(),
            "ports find failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );

        let body: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap_or_else(|e| {
            panic!(
                "stdout was not valid JSON ({e}): {}",
                String::from_utf8_lossy(&output.stdout)
            )
        });
        let items = body
            .as_array()
            .expect("ports find must emit a bare JSON array, like `networks list`");
        assert_eq!(items.len(), 2, "the device appears on two ports");
        assert_eq!(
            items[0]["port_idx"], 7,
            "the connected port must sort first"
        );
        assert_eq!(items[0]["connected"], true);
        assert_eq!(items[1]["port_idx"], 2, "the stale record sorts last");
        assert_eq!(items[1]["connected"], false);

        let mut emitted: Vec<&str> = items[0]
            .as_object()
            .expect("row must be a JSON object")
            .keys()
            .map(String::as_str)
            .collect();
        emitted.sort_unstable();
        let mut declared: Vec<&str> = unifi_cli::fields::names(unifi_cli::fields::PORTS_FIND);
        declared.sort_unstable();
        assert_eq!(
            emitted, declared,
            "ports find rows must carry exactly the PORTS_FIND field set"
        );
    }

    // Ambiguity is judged by port occupancy, not by how many client records a
    // name matches: `office` genuinely matches two devices here, and both
    // are actually attached to a switch port (unlike the "one interface
    // never shows up" fixtures below), so this must still exit 6 (conflict)
    // and name both candidates. Modeled on a live-controller case: two
    // physically distinct office devices sharing a name on the same switch.
    #[tokio::test]
    async fn ports_find_ambiguous_name_exits_with_conflict() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/sta"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [
                    {"_id": "1", "mac": "aa:bb:cc:dd:ee:20", "name": "office-ap", "ip": "192.0.2.6"},
                    {"_id": "2", "mac": "aa:bb:cc:dd:ee:21", "name": "Main-Office", "ip": "192.0.2.7"}
                ]
            })))
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/device"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [{
                    "mac": "aa:bb:cc:dd:06:43", "name": "USW Pro XG 8 PoE",
                    "port_table": [
                        {"port_idx": 3, "last_connection": {"mac": "aa:bb:cc:dd:ee:20", "connected": true}},
                        {"port_idx": 4, "last_connection": {"mac": "aa:bb:cc:dd:ee:21", "connected": true}}
                    ]
                }]
            })))
            .mount(&server)
            .await;

        let output = std::process::Command::new(env!("CARGO_BIN_EXE_unifi"))
            .args([
                "--host",
                &server.uri(),
                "--api-key",
                "test-key",
                "ports",
                "find",
                "office",
            ])
            .output()
            .expect("failed to run the unifi binary");

        assert_eq!(
            output.status.code(),
            Some(6),
            "an ambiguous name must exit 6 (conflict), got {:?}\nstderr: {}",
            output.status.code(),
            String::from_utf8_lossy(&output.stderr)
        );
        let stderr = String::from_utf8_lossy(&output.stderr);
        let last_line = stderr.trim_end().lines().last().unwrap_or("");
        let envelope: serde_json::Value =
            serde_json::from_str(last_line).expect("last stderr line must be valid JSON");
        assert_eq!(envelope["error"]["kind"], "conflict");
        let message = envelope["error"]["message"]
            .as_str()
            .expect("error envelope must carry a message");
        assert!(message.contains("office-ap"), "got: {message}");
        assert!(message.contains("Main-Office"), "got: {message}");
    }

    // A device whose wired and wireless interfaces share a name: `garage-pi`
    // matches two client records (a Raspberry Pi's wired and wireless
    // interfaces, MACs one bit apart in the last octet), but only the wired
    // interface ever shows up in a port table. That must resolve cleanly to
    // the one candidate that is actually on a port, not conflict.
    #[tokio::test]
    async fn ports_find_name_matches_two_clients_only_one_on_a_port_resolves_without_conflict() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/sta"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [
                    {"_id": "1", "mac": "aa:bb:cc:dd:ee:10", "name": "garage-pi", "ip": "192.0.2.5"},
                    {"_id": "2", "mac": "aa:bb:cc:dd:ee:11", "name": "garage-pi", "ip": "192.0.2.9"}
                ]
            })))
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/device"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [{
                    "mac": "aa:bb:cc:dd:06:43", "name": "USW Pro XG 8 PoE",
                    "port_table": [
                        {"port_idx": 5, "last_connection": {"mac": "aa:bb:cc:dd:ee:10", "connected": true}}
                    ]
                }]
            })))
            .mount(&server)
            .await;

        let output = std::process::Command::new(env!("CARGO_BIN_EXE_unifi"))
            .args([
                "--host",
                &server.uri(),
                "--api-key",
                "test-key",
                "ports",
                "find",
                "garage-pi",
                "-o",
                "json",
            ])
            .output()
            .expect("failed to run the unifi binary");
        assert!(
            output.status.success(),
            "ports find must resolve the single ported candidate, not conflict: {}",
            String::from_utf8_lossy(&output.stderr)
        );

        let items: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap_or_else(|e| {
            panic!(
                "stdout was not valid JSON ({e}): {}",
                String::from_utf8_lossy(&output.stdout)
            )
        });
        let items = items
            .as_array()
            .expect("ports find must emit a bare JSON array");
        assert_eq!(items.len(), 1, "only the wired interface is on a port");
        assert_eq!(items[0]["port_idx"], 5);
        assert_eq!(items[0]["connected"], true);
    }

    // The other client record sharing the name never appears in any port
    // table at all: not "only the wireless interface", but no candidate on a
    // port whatsoever, so this must be not_found, not a conflict.
    #[tokio::test]
    async fn ports_find_name_matches_clients_none_on_a_port_is_not_found() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/sta"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [
                    {"_id": "1", "mac": "aa:bb:cc:dd:ee:10", "name": "lobby-display", "ip": "192.0.2.15"},
                    {"_id": "2", "mac": "aa:bb:cc:dd:ee:11", "name": "lobby-display", "ip": "192.0.2.16"}
                ]
            })))
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/device"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [{
                    "mac": "aa:bb:cc:dd:06:43", "name": "USW Pro XG 8 PoE",
                    "port_table": [
                        {"port_idx": 1, "last_connection": {"mac": "11:22:33:44:55:66", "connected": true}}
                    ]
                }]
            })))
            .mount(&server)
            .await;

        let output = std::process::Command::new(env!("CARGO_BIN_EXE_unifi"))
            .args([
                "--host",
                &server.uri(),
                "--api-key",
                "test-key",
                "ports",
                "find",
                "lobby-display",
            ])
            .output()
            .expect("failed to run the unifi binary");

        assert_eq!(
            output.status.code(),
            Some(4),
            "neither candidate is on any port, so this must exit 4 (not_found), got {:?}\nstderr: {}",
            output.status.code(),
            String::from_utf8_lossy(&output.stderr)
        );
        let stderr = String::from_utf8_lossy(&output.stderr);
        let last_line = stderr.trim_end().lines().last().unwrap_or("");
        let envelope: serde_json::Value =
            serde_json::from_str(last_line).expect("last stderr line must be valid JSON");
        assert_eq!(envelope["error"]["kind"], "not_found");
        let message = envelope["error"]["message"]
            .as_str()
            .expect("error envelope must carry a message");
        assert!(message.contains("lobby-display"), "got: {message}");
    }

    // `find`'s JSON output has always carried `connected`; only the text
    // table lacked it, leaving the connected-first sort order as the sole
    // (easy-to-miss) signal for which row is the device's *current* port,
    // a distinction that matters because this lookup feeds the destructive
    // `ports cycle`. Two distinctly-named single-port devices (rather than
    // one device with two ports) so each rendered row can be identified by
    // its device name, independent of the connected-first sort this test
    // does not itself re-verify (that is `ports_find_by_mac_sorts_connected_first_and_skips_client_lookup`'s job).
    #[tokio::test]
    async fn ports_find_text_output_shows_connected_column() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/device"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [
                    {"mac": "aa:bb:cc:dd:ee:01", "name": "SwitchConnected",
                     "port_table": [
                        {"port_idx": 7, "last_connection": {"mac": "aa:bb:cc:dd:ee:10", "connected": true}}
                     ]},
                    {"mac": "aa:bb:cc:dd:ee:02", "name": "SwitchStale",
                     "port_table": [
                        {"port_idx": 2, "last_connection": {"mac": "aa:bb:cc:dd:ee:10", "connected": false}}
                     ]}
                ]
            })))
            .mount(&server)
            .await;

        let output = std::process::Command::new(env!("CARGO_BIN_EXE_unifi"))
            .args([
                "--host",
                &server.uri(),
                "--api-key",
                "test-key",
                "ports",
                "find",
                "aa:bb:cc:dd:ee:10",
                "-o",
                "text",
            ])
            .output()
            .expect("failed to run the unifi binary");
        assert!(
            output.status.success(),
            "ports find failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );

        let stdout = String::from_utf8_lossy(&output.stdout).into_owned();

        let header = stdout
            .lines()
            .find(|l| l.contains("Device"))
            .expect("text output must have a header row containing \"Device\"");
        assert!(
            header.contains("Connected"),
            "find's header must carry a Connected column: {header}"
        );

        let connected_row = stdout
            .lines()
            .find(|l| l.contains("SwitchConnected"))
            .expect("expected a row for the connected device");
        let stale_row = stdout
            .lines()
            .find(|l| l.contains("SwitchStale"))
            .expect("expected a row for the stale device");

        assert!(
            connected_row.trim_end().ends_with("yes"),
            "the connected row's Connected column must render \"yes\": {connected_row}"
        );
        assert!(
            stale_row.trim_end().ends_with('-'),
            "the stale row's Connected column must render \"-\": {stale_row}"
        );
    }

    // --- Ports cycle (mutation orchestration) ---
    //
    // `power_cycle_port_sends_correct_command` (in `client_api` above) only
    // covers the client method's endpoint and body. Nothing exercised the
    // orchestration in `commands::ports::cycle` that decides *whether* to call
    // it at all, and that orchestration is the only place in this CLI that
    // cuts power to physical hardware. These four cases pin down the guard-rail
    // ordering (find_port -> check_cyclable -> confirm -> POST) as a tested
    // property rather than a code-reading exercise: the `.expect(0)` mounts on
    // decline/conflict/not-found assert, via wiremock's mount-drop
    // verification, that no HTTP write happens on any of the three
    // non-cycling paths.

    #[tokio::test]
    async fn ports_cycle_confirmed_cycles_the_port() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/device"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [{
                    "mac": "aa:bb:cc:dd:06:43", "name": "USW-24-PoE",
                    "port_table": [{
                        "port_idx": 5, "port_poe": true, "poe_mode": "auto",
                        "poe_enable": true
                    }]
                }]
            })))
            .expect(1)
            .mount(&server)
            .await;
        Mock::given(method("POST"))
            .and(path("/proxy/network/api/s/default/cmd/devmgr"))
            .and(body_json(serde_json::json!({
                "cmd": "power-cycle",
                "mac": "aa:bb:cc:dd:06:43",
                "port_idx": 5
            })))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": []
            })))
            .expect(1)
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        let outcome =
            unifi_cli::commands::ports::cycle(&client, "aa:bb:cc:dd:06:43", 5, out_table(), |_| {
                Ok(true)
            })
            .await
            .unwrap();
        assert_eq!(outcome, unifi_cli::commands::ports::CycleOutcome::Cycled);
    }

    #[tokio::test]
    async fn ports_cycle_declined_never_posts() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/device"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [{
                    "mac": "aa:bb:cc:dd:06:43", "name": "USW-24-PoE",
                    "port_table": [{
                        "port_idx": 5, "port_poe": true, "poe_mode": "auto",
                        "poe_enable": true
                    }]
                }]
            })))
            .expect(1)
            .mount(&server)
            .await;
        Mock::given(method("POST"))
            .and(path("/proxy/network/api/s/default/cmd/devmgr"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": []
            })))
            .expect(0)
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        let outcome =
            unifi_cli::commands::ports::cycle(&client, "aa:bb:cc:dd:06:43", 5, out_table(), |_| {
                Ok(false)
            })
            .await
            .unwrap();
        assert_eq!(outcome, unifi_cli::commands::ports::CycleOutcome::Declined);
    }

    #[tokio::test]
    async fn ports_cycle_non_poe_port_is_conflict_and_never_posts() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/device"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [{
                    "mac": "aa:bb:cc:dd:06:43", "name": "USW-Lite-8",
                    "port_table": [{"port_idx": 9, "port_poe": false}]
                }]
            })))
            .expect(1)
            .mount(&server)
            .await;
        Mock::given(method("POST"))
            .and(path("/proxy/network/api/s/default/cmd/devmgr"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": []
            })))
            .expect(0)
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        // The confirm callback returns `Ok(true)` deliberately: `check_cyclable`
        // must reject before `confirm` is ever consulted, so a callback that
        // would approve proves nothing about ordering unless it's wired to run
        // second.
        let err =
            unifi_cli::commands::ports::cycle(&client, "aa:bb:cc:dd:06:43", 9, out_table(), |_| {
                Ok(true)
            })
            .await
            .unwrap_err();
        let api_err = err
            .downcast_ref::<unifi_cli::api::ApiError>()
            .unwrap_or_else(|| {
                panic!("cycle must reject a non-PoE port as an ApiError, got {err}")
            });
        assert!(
            matches!(api_err, unifi_cli::api::ApiError::Conflict(_)),
            "expected Conflict, got {api_err:?}"
        );
    }

    // Mirrors `ports_cycle_non_poe_port_is_conflict_and_never_posts` for the
    // third guard rail: a port that is PoE-capable and not administratively
    // off, but that the controller reports as not currently delivering power
    // (poe_enable: false). This is the fixture from the live UCG-Max finding
    // that motivated the guard; see `check_cyclable` in
    // `src/commands/ports.rs` for what was actually observed.
    #[tokio::test]
    async fn ports_cycle_poe_enable_false_is_conflict_and_never_posts() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/device"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [{
                    "mac": "aa:bb:cc:dd:ee:fe", "name": "USW Lite 8 PoE",
                    "port_table": [{
                        "port_idx": 4, "port_poe": true, "poe_mode": "auto",
                        "poe_enable": false, "poe_power": 0.0, "up": false
                    }]
                }]
            })))
            .expect(1)
            .mount(&server)
            .await;
        Mock::given(method("POST"))
            .and(path("/proxy/network/api/s/default/cmd/devmgr"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": []
            })))
            .expect(0)
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        // `Ok(true)` deliberately, same reasoning as the non-PoE case above:
        // proves `check_cyclable` rejects before `confirm` is ever consulted.
        let err =
            unifi_cli::commands::ports::cycle(&client, "aa:bb:cc:dd:ee:fe", 4, out_table(), |_| {
                Ok(true)
            })
            .await
            .unwrap_err();
        let api_err = err
            .downcast_ref::<unifi_cli::api::ApiError>()
            .unwrap_or_else(|| {
                panic!("cycle must reject a poe_enable=false port as an ApiError, got {err}")
            });
        assert!(
            matches!(api_err, unifi_cli::api::ApiError::Conflict(_)),
            "expected Conflict, got {api_err:?}"
        );
    }

    #[tokio::test]
    async fn ports_cycle_missing_port_is_not_found_and_never_posts() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/device"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [{
                    "mac": "aa:bb:cc:dd:06:43", "name": "USW-24-PoE",
                    "port_table": [{"port_idx": 1, "port_poe": true}]
                }]
            })))
            .expect(1)
            .mount(&server)
            .await;
        Mock::given(method("POST"))
            .and(path("/proxy/network/api/s/default/cmd/devmgr"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": []
            })))
            .expect(0)
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        let err = unifi_cli::commands::ports::cycle(
            &client,
            "aa:bb:cc:dd:06:43",
            99,
            out_table(),
            |_| Ok(true),
        )
        .await
        .unwrap_err();
        let api_err = err
            .downcast_ref::<unifi_cli::api::ApiError>()
            .unwrap_or_else(|| {
                panic!("cycle must report a missing port as an ApiError, got {err}")
            });
        assert!(
            matches!(api_err, unifi_cli::api::ApiError::NotFound(_)),
            "expected NotFound, got {api_err:?}"
        );
    }

    #[tokio::test]
    async fn list_events_returns_stat_event_records() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/event"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [
                    {"key": "EVT_AP_Connected", "msg": "AP connected", "subsystem": "wlan", "time": 200, "datetime": "2026-07-07T16:00:00Z"},
                    {"key": "EVT_SW_LostContact", "msg": "Switch lost contact", "subsystem": "lan", "time": 100, "datetime": "2026-07-07T15:00:00Z"}
                ]
            })))
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        let events = client.list_events(10).await.unwrap();
        assert_eq!(events.len(), 2);
        assert_eq!(events[0].key.as_deref(), Some("EVT_AP_Connected"));
    }

    // UniFi Network 9+ (UniFi OS) removed the legacy stat/event route, which now
    // returns api.err.NotFound (404). list_events must fall back to rest/alarm and
    // return the most recent `limit` records.
    #[tokio::test]
    async fn list_events_falls_back_to_alarms_on_404() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/event"))
            .respond_with(ResponseTemplate::new(404).set_body_json(serde_json::json!({
                "meta": {"rc": "error", "msg": "api.err.NotFound"},
                "data": []
            })))
            .expect(1)
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/rest/alarm"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [
                    {"key": "EVT_GW_Older", "msg": "older", "time": 100, "datetime": "a"},
                    {"key": "EVT_GW_Newest", "msg": "newest", "time": 300, "datetime": "c"},
                    {"key": "EVT_GW_Middle", "msg": "middle", "time": 200, "datetime": "b"}
                ]
            })))
            .expect(1)
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        let events = client.list_events(2).await.unwrap();
        // Most-recent-first, truncated to the requested limit.
        assert_eq!(events.len(), 2);
        assert_eq!(events[0].msg.as_deref(), Some("newest"));
        assert_eq!(events[1].msg.as_deref(), Some("middle"));
    }

    #[tokio::test]
    async fn list_events_propagates_non_404_errors() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/event"))
            .respond_with(ResponseTemplate::new(500).set_body_json(serde_json::json!({
                "meta": {"rc": "error", "msg": "api.err.ServerError"},
                "data": []
            })))
            .mount(&server)
            .await;

        let client = mock_client(&server).await;
        assert!(client.list_events(10).await.is_err());
    }
}

// --- Client construction tests ---

mod client_construction {
    #[test]
    fn new_with_https_host() {
        let client = unifi_cli::api::UnifiClient::new("https://unifi.example.com", "key123");
        assert!(client.is_ok());
    }

    #[test]
    fn new_with_http_host() {
        let client = unifi_cli::api::UnifiClient::new("http://localhost:8443", "key123");
        assert!(client.is_ok());
    }

    #[test]
    fn new_with_bare_host() {
        let client = unifi_cli::api::UnifiClient::new("unifi.local", "key123");
        assert!(client.is_ok());
    }

    #[test]
    fn new_strips_trailing_slash() {
        let client = unifi_cli::api::UnifiClient::new("https://unifi.local/", "key123");
        assert!(client.is_ok());
    }

    #[test]
    fn new_with_invalid_api_key() {
        let client = unifi_cli::api::UnifiClient::new("host", "bad\nkey");
        assert!(client.is_err());
    }
}

// --- An application the controller does not have ---
//
// UniFi OS does not 404 a request for an application that is not installed:
// it proxies the request to its own web UI, which answers 200 with an HTML
// page. Parsing that as JSON yields "error decoding response body", which
// names neither the endpoint nor the reason, so an agent cannot tell a
// missing application from a transport fault it should retry. These drive
// the real binary so the published envelope and exit code are observed.

mod unsupported_application {
    use wiremock::matchers::{method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    const UNIFI_OS_SHELL: &str =
        "<!DOCTYPE html><html><head><title>UniFi OS</title></head><body></body></html>";

    fn envelope(stderr: &str) -> serde_json::Value {
        let last_line = stderr.trim_end().lines().last().unwrap_or("");
        serde_json::from_str(last_line)
            .unwrap_or_else(|e| panic!("last stderr line must be valid JSON ({e}): {last_line:?}"))
    }

    #[tokio::test]
    async fn protect_cameras_list_reports_unsupported_when_the_controller_serves_html() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/protect/integration/v1/cameras"))
            .respond_with(
                ResponseTemplate::new(200).set_body_raw(UNIFI_OS_SHELL, "text/html; charset=utf-8"),
            )
            .mount(&server)
            .await;

        let output = std::process::Command::new(env!("CARGO_BIN_EXE_unifi"))
            .args([
                "--host",
                &server.uri(),
                "--api-key",
                "test-key",
                "protect",
                "cameras",
                "list",
            ])
            .output()
            .expect("failed to run the unifi binary");

        assert_eq!(
            output.status.code(),
            Some(4),
            "an absent application must exit 4, got {:?}\nstderr: {}",
            output.status.code(),
            String::from_utf8_lossy(&output.stderr)
        );
        let stderr = String::from_utf8_lossy(&output.stderr);
        let envelope = envelope(&stderr);
        assert_eq!(
            envelope["error"]["kind"], "unsupported",
            "an absent application is not a transport fault: {stderr}"
        );
        let message = envelope["error"]["message"]
            .as_str()
            .expect("error envelope must carry a message");
        assert!(
            message.contains("/proxy/protect/integration/v1/cameras"),
            "the message must name the endpoint that answered: {message}"
        );
        assert!(
            message.contains("text/html"),
            "the message must name what it answered with: {message}"
        );
        assert!(
            message.contains("Protect"),
            "a Protect endpoint must say which application is missing: {message}"
        );
    }

    // The same proxy behaviour on a Network endpoint. Nothing about the check
    // is Protect-specific, but only the Protect message carries the hint, so
    // this pins that a Network endpoint reports the kind without inventing an
    // application that is in fact installed.
    #[tokio::test]
    async fn a_legacy_endpoint_answering_html_reports_unsupported_without_a_protect_hint() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/device"))
            .respond_with(
                ResponseTemplate::new(200).set_body_raw(UNIFI_OS_SHELL, "text/html; charset=utf-8"),
            )
            .mount(&server)
            .await;

        let output = std::process::Command::new(env!("CARGO_BIN_EXE_unifi"))
            .args([
                "--host",
                &server.uri(),
                "--api-key",
                "test-key",
                "ports",
                "list",
            ])
            .output()
            .expect("failed to run the unifi binary");

        assert_eq!(
            output.status.code(),
            Some(4),
            "stderr: {}",
            String::from_utf8_lossy(&output.stderr)
        );
        let stderr = String::from_utf8_lossy(&output.stderr);
        let envelope = envelope(&stderr);
        assert_eq!(envelope["error"]["kind"], "unsupported");
        let message = envelope["error"]["message"].as_str().unwrap_or_default();
        assert!(
            message.contains("/proxy/network/api/s/default/stat/device"),
            "the message must name the endpoint that answered: {message}"
        );
        assert!(
            !message.contains("Protect"),
            "a Network endpoint must not be blamed on Protect: {message}"
        );
    }

    // A body that decodes is an answer, whatever the header says it is. A
    // controller behind a proxy that rewrites or drops the content type is
    // still serving the endpoint, so reporting it as an application the
    // controller does not have would be worse than the error this replaced:
    // it would name a cause that is not merely vague but wrong.
    #[tokio::test]
    async fn json_under_a_non_json_content_type_still_decodes() {
        for content_type in ["text/plain", "application/octet-stream"] {
            let server = MockServer::start().await;
            Mock::given(method("GET"))
                .and(path("/proxy/network/api/s/default/stat/device"))
                .respond_with(ResponseTemplate::new(200).set_body_raw(
                    r#"{"meta":{"rc":"ok"},"data":[{"mac":"aa:bb:cc:dd:ee:01","name":"SwitchA","port_table":[{"port_idx":1}]}]}"#,
                    content_type,
                ))
                .mount(&server)
                .await;

            let output = std::process::Command::new(env!("CARGO_BIN_EXE_unifi"))
                .args([
                    "--host",
                    &server.uri(),
                    "--api-key",
                    "test-key",
                    "ports",
                    "list",
                ])
                .output()
                .expect("failed to run the unifi binary");

            assert!(
                output.status.success(),
                "a JSON body served as {content_type} must still decode: {}",
                String::from_utf8_lossy(&output.stderr)
            );
            let body: serde_json::Value = serde_json::from_slice(&output.stdout)
                .unwrap_or_else(|e| panic!("stdout was not JSON ({e}) for {content_type}"));
            assert_eq!(body["items"][0]["device_name"], "SwitchA", "{content_type}");
        }
    }

    // A malformed body from an endpoint the controller does serve is a fault
    // in that controller, not a missing application, and must keep saying so.
    #[tokio::test]
    async fn a_broken_json_body_is_a_general_error_not_unsupported() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/device"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_raw(r#"{"meta":{"rc":"ok"},"data":["#, "application/json"),
            )
            .mount(&server)
            .await;

        let output = std::process::Command::new(env!("CARGO_BIN_EXE_unifi"))
            .args([
                "--host",
                &server.uri(),
                "--api-key",
                "test-key",
                "ports",
                "list",
            ])
            .output()
            .expect("failed to run the unifi binary");

        assert_eq!(
            output.status.code(),
            Some(1),
            "stderr: {}",
            String::from_utf8_lossy(&output.stderr)
        );
        let stderr = String::from_utf8_lossy(&output.stderr);
        let envelope = envelope(&stderr);
        assert_eq!(
            envelope["error"]["kind"], "general_error",
            "the endpoint is served, the body is broken: {stderr}"
        );
        let message = envelope["error"]["message"].as_str().unwrap_or_default();
        assert!(
            message.contains("/proxy/network/api/s/default/stat/device"),
            "the message must still name the endpoint: {message}"
        );
    }

    // The content-type check must not swallow a real JSON answer, including
    // one whose type carries a suffix or a charset.
    #[tokio::test]
    async fn a_json_content_type_still_decodes() {
        for content_type in [
            "application/json",
            "application/json; charset=utf-8",
            "application/vnd.api+json",
        ] {
            let server = MockServer::start().await;
            Mock::given(method("GET"))
                .and(path("/proxy/network/api/s/default/stat/device"))
                .respond_with(ResponseTemplate::new(200).set_body_raw(
                    r#"{"meta":{"rc":"ok"},"data":[{"mac":"aa:bb:cc:dd:ee:01","name":"SwitchA","port_table":[{"port_idx":1}]}]}"#,
                    content_type,
                ))
                .mount(&server)
                .await;

            let output = std::process::Command::new(env!("CARGO_BIN_EXE_unifi"))
                .args([
                    "--host",
                    &server.uri(),
                    "--api-key",
                    "test-key",
                    "ports",
                    "list",
                ])
                .output()
                .expect("failed to run the unifi binary");

            assert!(
                output.status.success(),
                "{content_type} must decode as JSON: {}",
                String::from_utf8_lossy(&output.stderr)
            );
            let body: serde_json::Value = serde_json::from_slice(&output.stdout)
                .unwrap_or_else(|e| panic!("stdout was not JSON ({e}) for {content_type}"));
            assert_eq!(body["items"][0]["device_name"], "SwitchA", "{content_type}");
        }
    }
}

// --- An event log the firmware no longer serves ---
//
// UniFi Network 9 answers stat/event with 404 api.err.NotFound, and some
// builds do not serve the rest/alarm fallback either: they reject the
// resource with 400 api.err.InvalidObject, the same answer a nonsense
// resource name gets. Reporting that verbatim tells a caller its request was
// malformed and invites it to retry with other parameters, when in truth no
// request would work. These drive the real binary so the published envelope
// and exit code are observed.

mod events_surface_removed {
    use wiremock::matchers::{method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    fn envelope(stderr: &str) -> serde_json::Value {
        let last_line = stderr.trim_end().lines().last().unwrap_or("");
        serde_json::from_str(last_line)
            .unwrap_or_else(|e| panic!("last stderr line must be valid JSON ({e}): {last_line:?}"))
    }

    fn run_events_list(server: &MockServer) -> std::process::Output {
        std::process::Command::new(env!("CARGO_BIN_EXE_unifi"))
            .args([
                "--host",
                &server.uri(),
                "--api-key",
                "test-key",
                "events",
                "list",
            ])
            .output()
            .expect("failed to run the unifi binary")
    }

    async fn mount_stat_event_404(server: &MockServer) {
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/event"))
            .respond_with(ResponseTemplate::new(404).set_body_json(serde_json::json!({
                "meta": {"rc": "error", "msg": "api.err.NotFound"},
                "data": []
            })))
            .mount(server)
            .await;
    }

    async fn mount_alarm(server: &MockServer, response: ResponseTemplate) {
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/rest/alarm"))
            .respond_with(response)
            .mount(server)
            .await;
    }

    #[tokio::test]
    async fn both_endpoints_gone_reports_unsupported_not_a_rejected_request() {
        let server = MockServer::start().await;
        mount_stat_event_404(&server).await;
        mount_alarm(
            &server,
            ResponseTemplate::new(400).set_body_json(serde_json::json!({
                "meta": {"rc": "error", "msg": "api.err.InvalidObject"},
                "data": []
            })),
        )
        .await;

        let output = run_events_list(&server);
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert_eq!(
            output.status.code(),
            Some(4),
            "an absent event surface must exit 4, not 5: {stderr}"
        );
        let envelope = envelope(&stderr);
        assert_eq!(
            envelope["error"]["kind"], "unsupported",
            "the request was fine, the endpoint is gone: {stderr}"
        );
        let message = envelope["error"]["message"]
            .as_str()
            .expect("error envelope must carry a message");
        assert!(
            message.contains("/proxy/network/api/s/default/stat/event"),
            "the message must name the endpoint the caller asked for: {message}"
        );
        assert!(
            message.contains("WebSocket"),
            "the message must say what event stream remains: {message}"
        );
        assert!(
            !message.contains("instead of JSON"),
            "this controller answered JSON, it just refused the resource: {message}"
        );
        assert!(
            !message.contains("Protect"),
            "a Network endpoint must not be blamed on Protect: {message}"
        );
    }

    // The fallback answering 404 means the same thing as its 400: the resource
    // is not there. Both arms must reach the same kind.
    #[tokio::test]
    async fn a_fallback_that_404s_reports_unsupported_too() {
        let server = MockServer::start().await;
        mount_stat_event_404(&server).await;
        mount_alarm(
            &server,
            ResponseTemplate::new(404).set_body_json(serde_json::json!({
                "meta": {"rc": "error", "msg": "api.err.NotFound"},
                "data": []
            })),
        )
        .await;

        let output = run_events_list(&server);
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert_eq!(output.status.code(), Some(4), "stderr: {stderr}");
        assert_eq!(envelope(&stderr)["error"]["kind"], "unsupported");
    }

    // The negative control for the 400 arm. A 400 that is not the controller
    // disowning the resource is a genuinely rejected request, and must keep
    // saying so: turning every 400 into `unsupported` would hide real faults
    // behind "this controller cannot do that".
    #[tokio::test]
    async fn a_fallback_rejecting_the_request_stays_a_client_error() {
        let server = MockServer::start().await;
        mount_stat_event_404(&server).await;
        mount_alarm(
            &server,
            ResponseTemplate::new(400).set_body_json(serde_json::json!({
                "meta": {"rc": "error", "msg": "api.err.InvalidPayload"},
                "data": []
            })),
        )
        .await;

        let output = run_events_list(&server);
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert_eq!(
            output.status.code(),
            Some(5),
            "a rejected request is not an absent endpoint: {stderr}"
        );
        let envelope = envelope(&stderr);
        assert_eq!(envelope["error"]["kind"], "client_error", "{stderr}");
        let message = envelope["error"]["message"].as_str().unwrap_or_default();
        assert!(
            message.contains("api.err.InvalidPayload"),
            "the controller's own reason must survive: {message}"
        );
    }

    // The positive control. A controller that does serve the fallback must
    // still get its events, so the check above cannot be passing by refusing
    // everything.
    #[tokio::test]
    async fn a_working_fallback_still_returns_events() {
        let server = MockServer::start().await;
        mount_stat_event_404(&server).await;
        mount_alarm(
            &server,
            ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [
                    {"key": "EVT_GW_Restarted", "msg": "Gateway restarted", "subsystem": "wan", "time": 300, "datetime": "2026-07-07T17:00:00Z"}
                ]
            })),
        )
        .await;

        let output = run_events_list(&server);
        assert!(
            output.status.success(),
            "a served fallback must succeed: {}",
            String::from_utf8_lossy(&output.stderr)
        );
        let body: serde_json::Value =
            serde_json::from_slice(&output.stdout).expect("stdout was not JSON");
        assert_eq!(body["items"][0]["key"], "EVT_GW_Restarted");
    }
}

// --- Ranking clients the controller published no counters for ---
//
// The live controller omits tx_bytes/rx_bytes for a substantial share of the
// clients it lists, so this is the common case rather than a corner of it.

mod clients_top_unknown_counters {
    use wiremock::matchers::{method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    /// One client that transferred a lot, one that reported a real zero, and one
    /// the controller published no counters for at all.
    async fn serving_a_mixed_population() -> MockServer {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/sta"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [
                    {"_id": "c1", "mac": "aa:bb:cc:dd:ee:01", "ip": "192.0.2.1",
                     "name": "Talker", "is_wired": true,
                     "tx_bytes": 500000, "rx_bytes": 600000},
                    {"_id": "c2", "mac": "aa:bb:cc:dd:ee:02", "ip": "192.0.2.2",
                     "name": "Silent", "is_wired": true},
                    {"_id": "c3", "mac": "aa:bb:cc:dd:ee:03", "ip": "192.0.2.3",
                     "name": "Measured Idle", "is_wired": true,
                     "tx_bytes": 0, "rx_bytes": 0}
                ]
            })))
            .mount(&server)
            .await;
        server
    }

    fn run(server_uri: &str, args: &[&str]) -> std::process::Output {
        let mut argv = vec!["--host", server_uri, "--api-key", "test-key"];
        argv.extend_from_slice(args);
        std::process::Command::new(env!("CARGO_BIN_EXE_unifi"))
            .args(argv)
            .output()
            .expect("failed to run the unifi binary")
    }

    #[tokio::test]
    async fn a_client_with_no_reported_counters_is_not_drawn_as_having_moved_nothing() {
        let server = serving_a_mixed_population().await;
        let stdout = String::from_utf8_lossy(
            &run(
                &server.uri(),
                &["clients", "top", "--limit", "10", "-o", "text"],
            )
            .stdout,
        )
        .into_owned();

        let silent = stdout
            .lines()
            .find(|l| l.contains("Silent"))
            .unwrap_or_else(|| panic!("no row for the client without counters:\n{stdout}"));
        assert!(
            !silent.contains("0 B"),
            "counters the controller never sent are unknown, and `0 B` claims a \
             measurement nobody made: {silent}"
        );

        // The negative control: a client that really did report zero must keep
        // saying so, or the fix has simply hidden every zero.
        let idle = stdout
            .lines()
            .find(|l| l.contains("Measured Idle"))
            .unwrap_or_else(|| panic!("no row for the idle client:\n{stdout}"));
        assert!(
            idle.contains("0 B"),
            "a client that did report zero has been measured: {idle}"
        );
    }

    #[tokio::test]
    async fn an_unrankable_client_does_not_displace_one_that_can_be_ranked() {
        let server = serving_a_mixed_population().await;
        let stdout = String::from_utf8_lossy(
            &run(
                &server.uri(),
                &["clients", "top", "--limit", "10", "-o", "text"],
            )
            .stdout,
        )
        .into_owned();

        let row_of = |name: &str| {
            stdout
                .lines()
                .position(|l| l.contains(name))
                .unwrap_or_else(|| panic!("no row for {name}:\n{stdout}"))
        };
        assert!(
            row_of("Talker") < row_of("Measured Idle"),
            "a ranking by traffic still ranks what it can:\n{stdout}"
        );
        assert!(
            row_of("Measured Idle") < row_of("Silent"),
            "a client that cannot be ranked belongs after every client that \
             can, not interleaved with them:\n{stdout}"
        );
    }

    #[tokio::test]
    async fn the_total_is_not_a_number_when_neither_half_is() {
        let server = serving_a_mixed_population().await;
        let output = run(
            &server.uri(),
            &["clients", "top", "--limit", "10", "-o", "json"],
        );
        let body: serde_json::Value =
            serde_json::from_slice(&output.stdout).expect("stdout was not JSON");
        let items = body.as_array().expect("clients top emits an array");
        let silent = items
            .iter()
            .find(|c| c["name"] == "Silent")
            .expect("the client without counters must still be listed");

        assert!(
            silent["tx_bytes"].is_null() && silent["rx_bytes"].is_null(),
            "{silent}"
        );
        assert!(
            silent["total_bytes"].is_null(),
            "a total of two unknowns is unknown, and `0` next to two nulls is a \
             contradiction in one object: {silent}"
        );
    }
}

// --- The Protect camera surface ---
//
// There is no Protect application to test against, so these drive the real
// binary against a stand-in that serves the payloads Protect's own API is
// documented to return. That proves what the tool does with a given payload,
// which is where every finding below lived; it does not prove which payloads
// Protect actually sends.

mod protect_cameras {
    use wiremock::matchers::{method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    const CAMERAS_PATH: &str = "/proxy/protect/integration/v1/cameras";

    fn run(server_uri: &str, args: &[&str]) -> std::process::Output {
        let mut argv = vec!["--host", server_uri, "--api-key", "test-key"];
        argv.extend_from_slice(args);
        std::process::Command::new(env!("CARGO_BIN_EXE_unifi"))
            .args(argv)
            .output()
            .expect("failed to run the unifi binary")
    }

    async fn serving(body: serde_json::Value) -> MockServer {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path(CAMERAS_PATH))
            .respond_with(ResponseTemplate::new(200).set_body_json(body))
            .mount(&server)
            .await;
        server
    }

    #[tokio::test]
    async fn the_camera_list_uses_the_same_envelope_as_every_other_list() {
        let server = serving(serde_json::json!([
            {"id": "aaaaaaaaaaaaaaaaaaaaaaaa", "name": "Front Door", "state": "CONNECTED"}
        ]))
        .await;

        let output = run(&server.uri(), &["protect", "cameras", "list", "-o", "json"]);
        assert!(output.status.success());
        let body: serde_json::Value =
            serde_json::from_slice(&output.stdout).expect("stdout was not JSON");

        assert_eq!(
            body["items"][0]["name"], "Front Door",
            "a consumer reading `items` must not have to special-case cameras: {body}"
        );
        assert_eq!(body["total"], 1, "{body}");
    }

    // Same contract check the rest of the read-only surface gets: what the
    // schema publishes for these commands must be what they emit.
    #[tokio::test]
    async fn the_camera_list_matches_the_schema_it_publishes() {
        let server = serving(serde_json::json!([{
            "id": "aaaaaaaaaaaaaaaaaaaaaaaa", "name": "Front Door",
            "mac": "AABBCCDDEEFF", "state": "CONNECTED", "modelKey": "camera",
            "isMicEnabled": true, "videoMode": "default"
        }]))
        .await;

        let output = run(&server.uri(), &["protect", "cameras", "list", "-o", "json"]);
        let body: serde_json::Value =
            serde_json::from_slice(&output.stdout).expect("stdout was not JSON");
        crate::assert_schema_matches("protect cameras list", &body);
    }

    #[tokio::test]
    async fn the_camera_detail_matches_the_schema_it_publishes() {
        let camera = serde_json::json!({
            "id": "aaaaaaaaaaaaaaaaaaaaaaaa", "name": "Front Door",
            "mac": "AABBCCDDEEFF", "state": "CONNECTED", "modelKey": "camera",
            "isMicEnabled": true, "videoMode": "default",
            "featureFlags": {"hasHdr": true, "hasMic": true}
        });
        // The name is resolved against the listing, then the detail fetched by id.
        let server = serving(serde_json::json!([camera])).await;
        Mock::given(method("GET"))
            .and(path(format!("{CAMERAS_PATH}/aaaaaaaaaaaaaaaaaaaaaaaa")))
            .respond_with(ResponseTemplate::new(200).set_body_json(camera))
            .mount(&server)
            .await;

        let output = run(
            &server.uri(),
            &["protect", "cameras", "show", "Front Door", "-o", "json"],
        );
        assert!(
            output.status.success(),
            "cameras show failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );
        let body: serde_json::Value =
            serde_json::from_slice(&output.stdout).expect("stdout was not JSON");
        crate::assert_schema_matches("protect cameras show", &body);
    }

    #[tokio::test]
    async fn a_camera_that_did_not_report_its_mic_is_not_reported_as_muted() {
        let server = serving(serde_json::json!([
            {"id": "aaaaaaaaaaaaaaaaaaaaaaaa", "name": "Front Door", "state": "CONNECTED"}
        ]))
        .await;

        let output = run(&server.uri(), &["protect", "cameras", "list", "-o", "json"]);
        let body: serde_json::Value =
            serde_json::from_slice(&output.stdout).expect("stdout was not JSON");

        assert!(
            body["items"][0]["mic_enabled"].is_null(),
            "an unreported flag is unknown, and `false` cannot be told apart \
             from a camera that really has its mic off: {body}"
        );
    }

    #[tokio::test]
    async fn a_camera_that_reported_its_mic_still_says_so() {
        let server = serving(serde_json::json!([
            {"id": "aaaaaaaaaaaaaaaaaaaaaaaa", "name": "Front Door", "isMicEnabled": false}
        ]))
        .await;

        let output = run(&server.uri(), &["protect", "cameras", "list", "-o", "json"]);
        let body: serde_json::Value =
            serde_json::from_slice(&output.stdout).expect("stdout was not JSON");

        assert_eq!(
            body["items"][0]["mic_enabled"], false,
            "a flag the camera did report must survive: {body}"
        );
    }

    #[tokio::test]
    async fn one_camera_matching_a_name_resolves_to_it() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path(CAMERAS_PATH))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!([
                {"id": "aaaaaaaaaaaaaaaaaaaaaaaa", "name": "Front Door"},
                {"id": "bbbbbbbbbbbbbbbbbbbbbbbb", "name": "Back Door"}
            ])))
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path(format!("{CAMERAS_PATH}/aaaaaaaaaaaaaaaaaaaaaaaa")))
            .respond_with(ResponseTemplate::new(200).set_body_json(
                serde_json::json!({"id": "aaaaaaaaaaaaaaaaaaaaaaaa", "name": "Front Door"}),
            ))
            .mount(&server)
            .await;

        let output = run(
            &server.uri(),
            &["protect", "cameras", "show", "Front Door", "-o", "json"],
        );
        assert!(
            output.status.success(),
            "an unambiguous name must resolve: {}",
            String::from_utf8_lossy(&output.stderr)
        );
        let body: serde_json::Value =
            serde_json::from_slice(&output.stdout).expect("stdout was not JSON");
        assert_eq!(body["id"], "aaaaaaaaaaaaaaaaaaaaaaaa");
    }

    #[tokio::test]
    async fn a_name_two_cameras_share_is_refused_rather_than_guessed() {
        let server = serving(serde_json::json!([
            {"id": "aaaaaaaaaaaaaaaaaaaaaaaa", "name": "Front Door"},
            {"id": "bbbbbbbbbbbbbbbbbbbbbbbb", "name": "Front Door"}
        ]))
        .await;

        let output = run(
            &server.uri(),
            &["protect", "cameras", "show", "Front Door", "-o", "json"],
        );

        assert!(
            !output.status.success(),
            "acting on whichever camera was listed first is a silent choice \
             the caller never made"
        );
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(
            stderr.contains("aaaaaaaaaaaaaaaaaaaaaaaa")
                && stderr.contains("bbbbbbbbbbbbbbbbbbbbbbbb"),
            "both candidates must be named so the caller can pick one: {stderr}"
        );
    }

    #[tokio::test]
    async fn the_rtsps_listing_matches_the_schema_it_publishes() {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path(format!(
                "{CAMERAS_PATH}/aaaaaaaaaaaaaaaaaaaaaaaa/rtsps-stream"
            )))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "high": "rtsps://192.0.2.10:7441/high",
                "medium": "rtsps://192.0.2.10:7441/medium",
                "low": "rtsps://192.0.2.10:7441/low",
                "package": "rtsps://192.0.2.10:7441/package"
            })))
            .mount(&server)
            .await;

        let output = run(
            &server.uri(),
            &[
                "protect",
                "rtsps",
                "list",
                "aaaaaaaaaaaaaaaaaaaaaaaa",
                "-o",
                "json",
            ],
        );
        assert!(
            output.status.success(),
            "rtsps list failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );
        let body: serde_json::Value =
            serde_json::from_slice(&output.stdout).expect("stdout was not JSON");
        crate::assert_schema_matches("protect rtsps list", &body);
    }

    #[tokio::test]
    async fn a_stream_the_controller_did_not_return_is_not_reported_as_created() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path(format!(
                "{CAMERAS_PATH}/aaaaaaaaaaaaaaaaaaaaaaaa/rtsps-stream"
            )))
            // Asked for high and medium; only high comes back.
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "high": "rtsps://192.0.2.10:7441/abc"
            })))
            .mount(&server)
            .await;

        let output = run(
            &server.uri(),
            &[
                "protect",
                "rtsps",
                "create",
                "aaaaaaaaaaaaaaaaaaaaaaaa",
                "--quality",
                "high,medium",
                "-o",
                "json",
            ],
        );

        assert!(
            !output.status.success(),
            "a request carried out in part must not exit 0: {}",
            String::from_utf8_lossy(&output.stdout)
        );
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(
            stderr.contains("medium"),
            "the quality that was not created must be named: {stderr}"
        );
    }

    #[tokio::test]
    async fn every_stream_asked_for_coming_back_is_a_plain_success() {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path(format!(
                "{CAMERAS_PATH}/aaaaaaaaaaaaaaaaaaaaaaaa/rtsps-stream"
            )))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "high": "rtsps://192.0.2.10:7441/abc",
                "medium": "rtsps://192.0.2.10:7441/def"
            })))
            .mount(&server)
            .await;

        let output = run(
            &server.uri(),
            &[
                "protect",
                "rtsps",
                "create",
                "aaaaaaaaaaaaaaaaaaaaaaaa",
                "--quality",
                "high,medium",
                "-o",
                "json",
            ],
        );

        assert!(
            output.status.success(),
            "nothing was missing: {}",
            String::from_utf8_lossy(&output.stderr)
        );
        let body: serde_json::Value =
            serde_json::from_slice(&output.stdout).expect("stdout was not JSON");
        assert_eq!(body["status"], "ok", "{body}");
        assert_eq!(body["not_created"].as_array().map(|a| a.len()), Some(0));

        // The schema's published output_fields must exactly match the keys this
        // command emits, the same property `ports show` holds itself to. The
        // fields that say a request was only half carried out are worth nothing
        // if an agent reading the contract cannot learn they exist.
        let schema_output = std::process::Command::new(env!("CARGO_BIN_EXE_unifi"))
            .arg("schema")
            .output()
            .expect("failed to run unifi schema");
        let schema: serde_json::Value = serde_json::from_slice(&schema_output.stdout)
            .expect("unifi schema must print valid JSON");
        let create = schema["commands"]
            .as_array()
            .expect("schema must have a commands array")
            .iter()
            .find(|c| c["name"] == "protect rtsps create")
            .expect("schema must publish a \"protect rtsps create\" command");
        let mut declared: Vec<&str> = create["output_fields"]
            .as_array()
            .expect("protect rtsps create must declare output_fields")
            .iter()
            .map(|f| f["name"].as_str().expect("output field must have a name"))
            .collect();
        declared.sort_unstable();
        let mut emitted: Vec<&str> = body
            .as_object()
            .expect("output must be a JSON object")
            .keys()
            .map(String::as_str)
            .collect();
        emitted.sort_unstable();
        assert_eq!(
            emitted, declared,
            "protect rtsps create output_fields in the schema must exactly match \
             the keys it emits"
        );
    }

    /// Stand in for the cookie-authenticated direct Protect API that `--full`
    /// uses: a login that hands back a TOKEN cookie, plus one camera.
    async fn serving_full(camera: serde_json::Value) -> MockServer {
        let server = MockServer::start().await;
        Mock::given(method("POST"))
            .and(path("/api/auth/login"))
            .respond_with(
                ResponseTemplate::new(200)
                    .insert_header("set-cookie", "TOKEN=stand-in; Path=/")
                    .set_body_json(serde_json::json!({})),
            )
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path(format!("{CAMERAS_PATH}/aaaaaaaaaaaaaaaaaaaaaaaa")))
            .respond_with(ResponseTemplate::new(200).set_body_json(
                serde_json::json!({"id": "aaaaaaaaaaaaaaaaaaaaaaaa", "name": "Front Door"}),
            ))
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .and(path("/proxy/protect/api/cameras/aaaaaaaaaaaaaaaaaaaaaaaa"))
            .respond_with(ResponseTemplate::new(200).set_body_json(camera))
            .mount(&server)
            .await;
        server
    }

    fn show_full(server_uri: &str) -> std::process::Output {
        std::process::Command::new(env!("CARGO_BIN_EXE_unifi"))
            .args([
                "--host",
                server_uri,
                "--api-key",
                "test-key",
                "--username",
                "stand-in",
                "--password",
                "stand-in",
                "-o",
                "text",
                "protect",
                "cameras",
                "show",
                "aaaaaaaaaaaaaaaaaaaaaaaa",
                "--full",
            ])
            .output()
            .expect("failed to run the unifi binary")
    }

    #[tokio::test]
    async fn a_storage_figure_the_camera_did_not_report_is_not_shown_as_zero() {
        let server = serving_full(serde_json::json!({
            "id": "aaaaaaaaaaaaaaaaaaaaaaaa",
            "name": "Front Door",
            "hqBytesPerDay": 12_000_000_000u64
        }))
        .await;

        let output = show_full(&server.uri());
        assert!(
            output.status.success(),
            "stderr: {}",
            String::from_utf8_lossy(&output.stderr)
        );
        let stdout = String::from_utf8_lossy(&output.stdout);
        let storage = stdout
            .lines()
            .find(|l| l.contains("Storage:"))
            .unwrap_or_else(|| panic!("no storage line:\n{stdout}"));
        assert!(
            storage.contains("- LQ"),
            "a figure the camera never sent is unknown, not a claim that the \
             low-quality stream costs nothing: {storage}"
        );
    }

    #[tokio::test]
    async fn both_storage_figures_are_shown_when_the_camera_reports_them() {
        let server = serving_full(serde_json::json!({
            "id": "aaaaaaaaaaaaaaaaaaaaaaaa",
            "name": "Front Door",
            "hqBytesPerDay": 12_000_000_000u64,
            "lqBytesPerDay": 1_000_000_000u64
        }))
        .await;

        let stdout = String::from_utf8_lossy(&show_full(&server.uri()).stdout).into_owned();
        let storage = stdout
            .lines()
            .find(|l| l.contains("Storage:"))
            .unwrap_or_else(|| panic!("no storage line:\n{stdout}"));
        assert!(
            storage.contains("GB HQ") && storage.contains("MB LQ"),
            "reported figures must both render: {storage}"
        );
    }

    #[tokio::test]
    async fn a_camera_silent_about_recording_does_not_report_that_it_is_not() {
        let server = serving_full(serde_json::json!({
            "id": "aaaaaaaaaaaaaaaaaaaaaaaa",
            "name": "Front Door"
        }))
        .await;

        let stdout = String::from_utf8_lossy(&show_full(&server.uri()).stdout).into_owned();
        let recording = stdout
            .lines()
            .find(|l| l.contains("Recording:"))
            .unwrap_or_else(|| panic!("no recording line:\n{stdout}"));
        assert!(
            recording.contains('-') && !recording.contains("no"),
            "a camera that said nothing about recording has not said it is \
             idle: {recording}"
        );
    }

    fn show_full_json(server_uri: &str) -> serde_json::Value {
        let output = std::process::Command::new(env!("CARGO_BIN_EXE_unifi"))
            .args([
                "--host",
                server_uri,
                "--api-key",
                "test-key",
                "--username",
                "stand-in",
                "--password",
                "stand-in",
                "-o",
                "json",
                "protect",
                "cameras",
                "show",
                "aaaaaaaaaaaaaaaaaaaaaaaa",
                "--full",
            ])
            .output()
            .expect("failed to run the unifi binary");
        serde_json::from_slice(&output.stdout).unwrap_or_else(|e| {
            panic!(
                "stdout was not JSON ({e}): {}\nstderr: {}",
                String::from_utf8_lossy(&output.stdout),
                String::from_utf8_lossy(&output.stderr)
            )
        })
    }

    /// The JSON-only siblings of the flags above. They reach an agent rather
    /// than a person, where a bare `false` is taken at face value.
    #[tokio::test]
    async fn the_flags_only_json_carries_are_null_when_the_camera_omits_them() {
        let server = serving_full(serde_json::json!({
            "id": "aaaaaaaaaaaaaaaaaaaaaaaa",
            "name": "Front Door",
            "recordingSettings": {"mode": "always"},
            "channels": [{"id": 0, "name": "High"}]
        }))
        .await;

        let body = show_full_json(&server.uri());
        assert!(
            body["motion_detected"].is_null(),
            "a camera that did not report motion has not reported stillness: {body}"
        );
        assert!(
            body["recording_settings"]["motion_detection"].is_null(),
            "settings that never mentioned motion detection have not said it is \
             off: {body}"
        );
        assert!(
            body["channels"][0]["enabled"].is_null(),
            "a channel whose state was not reported is not a disabled channel: {body}"
        );
    }

    #[tokio::test]
    async fn the_flags_only_json_carries_survive_when_the_camera_reports_them() {
        let server = serving_full(serde_json::json!({
            "id": "aaaaaaaaaaaaaaaaaaaaaaaa",
            "name": "Front Door",
            "isMotionDetected": false,
            "recordingSettings": {"mode": "always", "enableMotionDetection": true},
            "channels": [{"id": 0, "name": "High", "enabled": false}]
        }))
        .await;

        let body = show_full_json(&server.uri());
        assert_eq!(body["motion_detected"], false, "{body}");
        assert_eq!(
            body["recording_settings"]["motion_detection"], true,
            "{body}"
        );
        assert_eq!(body["channels"][0]["enabled"], false, "{body}");
    }

    #[tokio::test]
    async fn a_camera_page_is_not_requested_when_the_id_is_already_an_id() {
        // Resolution short-circuits on a 24-char hex ID, so no listing is
        // served here at all: if the binary asked for one it would fail.
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path(format!("{CAMERAS_PATH}/aaaaaaaaaaaaaaaaaaaaaaaa")))
            .respond_with(ResponseTemplate::new(200).set_body_json(
                serde_json::json!({"id": "aaaaaaaaaaaaaaaaaaaaaaaa", "name": "Front Door"}),
            ))
            .mount(&server)
            .await;

        let output = run(
            &server.uri(),
            &[
                "protect",
                "cameras",
                "show",
                "aaaaaaaaaaaaaaaaaaaaaaaa",
                "-o",
                "json",
            ],
        );
        assert!(
            output.status.success(),
            "an ID must resolve without a listing: {}",
            String::from_utf8_lossy(&output.stderr)
        );
    }
}

// A schema that does not describe the output is worse than no schema: it sends
// an agent looking for a key that never arrives, or hides one that does. Both
// halves were live defects, found by comparing declared fields against a real
// controller's output by hand. These guards do that comparison in CI instead.
mod schema_contract {
    use super::*;

    const SYSINFO: &str = "/proxy/network/api/s/default/stat/sysinfo";

    async fn mount_sysinfo(server: &MockServer) {
        Mock::given(method("GET"))
            .and(path(SYSINFO))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [{
                    "hostname": "UCG-Ultra", "version": "10.1.85",
                    "timezone": "Europe/Amsterdam", "uptime": 1737960
                }]
            })))
            .mount(server)
            .await;
    }

    /// Serve `stat/sysinfo`, and answer `/api/system` with `host_system` when
    /// given. Leaving it out models a host system that could not be reached,
    /// which wiremock answers with a 404.
    async fn serving_system(host_system: Option<serde_json::Value>) -> MockServer {
        let server = MockServer::start().await;
        mount_sysinfo(&server).await;
        if let Some(body) = host_system {
            Mock::given(method("GET"))
                .and(path("/api/system"))
                .respond_with(ResponseTemplate::new(200).set_body_json(body))
                .mount(&server)
                .await;
        }
        server
    }

    #[tokio::test]
    async fn system_info_json_matches_schema_output_fields() {
        let server = serving_system(Some(serde_json::json!({"deviceState": "online"}))).await;
        let body = run_json(&server, &["system", "info"]).await;
        assert_schema_matches("system info", &body);
    }

    #[tokio::test]
    async fn a_state_the_host_did_not_report_is_unknown_not_up_to_date() {
        let server = serving_system(Some(serde_json::json!({"name": "UCG Ultra"}))).await;
        let body = run_json(&server, &["system", "info"]).await;
        assert_eq!(
            body["update_available"],
            serde_json::Value::Null,
            "a host that reported no device state has not reported an up-to-date one: {body}"
        );
    }

    #[tokio::test]
    async fn a_host_system_that_could_not_be_reached_leaves_the_update_state_unknown() {
        let server = serving_system(None).await;
        let body = run_json(&server, &["system", "info"]).await;
        assert_eq!(
            body["update_available"],
            serde_json::Value::Null,
            "a check that could not be made is not a check that came back clean: {body}"
        );
    }

    // Positive control for the two above: a state the host did report must
    // still settle the question, in both directions. A fix that hid unknowns
    // by never answering would pass those tests and fail these.
    #[tokio::test]
    async fn a_reported_state_still_settles_the_question() {
        let up_to_date = serving_system(Some(serde_json::json!({"deviceState": "online"}))).await;
        let body = run_json(&up_to_date, &["system", "info"]).await;
        assert_eq!(body["update_available"], serde_json::json!(false));

        let waiting =
            serving_system(Some(serde_json::json!({"deviceState": "updateAvailable"}))).await;
        let body = run_json(&waiting, &["system", "info"]).await;
        assert_eq!(body["update_available"], serde_json::json!(true));
    }

    // The human surface has the same requirement: silence has always meant "up
    // to date", so an unknown state cannot also be silent.
    #[tokio::test]
    async fn text_output_says_unknown_rather_than_staying_silent() {
        let unknown = serving_system(Some(serde_json::json!({"name": "UCG Ultra"}))).await;
        let text = run_text(&unknown, &["system", "info"]);
        assert!(
            text.contains("Unknown"),
            "an unreported update state must be shown, not omitted: {text}"
        );

        let up_to_date = serving_system(Some(serde_json::json!({"deviceState": "online"}))).await;
        let text = run_text(&up_to_date, &["system", "info"]);
        assert!(
            !text.contains("Update:"),
            "a host that reported being up to date still needs no line: {text}"
        );
    }

    fn run_text(server: &MockServer, args: &[&str]) -> String {
        let uri = server.uri();
        let mut argv = vec!["--host", uri.as_str(), "--api-key", "test-key"];
        argv.extend_from_slice(args);
        argv.extend_from_slice(&["--output", "text"]);
        let output = std::process::Command::new(env!("CARGO_BIN_EXE_unifi"))
            .args(&argv)
            .output()
            .expect("failed to run the unifi binary");
        assert!(
            output.status.success(),
            "{} failed: {}",
            args.join(" "),
            String::from_utf8_lossy(&output.stderr)
        );
        String::from_utf8_lossy(&output.stdout).into_owned()
    }

    async fn serving_one_device() -> MockServer {
        let server = MockServer::start().await;
        Mock::given(method("GET"))
            .and(path("/proxy/network/api/s/default/stat/device"))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": [{
                    "mac": "aa:bb:cc:dd:06:43", "name": "Switch Lite 8 PoE",
                    "model": "USL8LP", "ip": "192.0.2.10", "state": 1,
                    "version": "7.1.20.16850", "uptime": 401234, "num_sta": 6
                }]
            })))
            .mount(&server)
            .await;
        server
    }

    #[tokio::test]
    async fn devices_show_json_matches_schema_output_fields() {
        let server = serving_one_device().await;
        let body = run_json(&server, &["devices", "show", "aa:bb:cc:dd:06:43"]).await;
        assert_schema_matches("devices show", &body);
    }

    // `firmware` is the name `devices list` publishes for this value, so an
    // agent that reads it there and asks this command for the same device must
    // find it under the same name.
    #[tokio::test]
    async fn devices_show_emits_the_firmware_it_declares() {
        let server = serving_one_device().await;
        let body = run_json(&server, &["devices", "show", "aa:bb:cc:dd:06:43"]).await;
        assert_eq!(body["firmware"], serde_json::json!("7.1.20.16850"));
        assert_eq!(
            body["firmware"], body["version"],
            "firmware and version are the same value under two names: {body}"
        );
    }

    // --- The rest of the read-only surface ---
    //
    // Two drifts were found by comparing declared fields against a real
    // controller by hand. Every remaining command that publishes output_fields
    // gets the same comparison here, so the next one cannot reach a release.

    async fn mount_legacy(server: &MockServer, endpoint: &str, data: serde_json::Value) {
        Mock::given(method("GET"))
            .and(path(format!("/proxy/network/api/s/default/{endpoint}")))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "meta": {"rc": "ok"},
                "data": data
            })))
            .mount(server)
            .await;
    }

    async fn serving_legacy(endpoint: &str, data: serde_json::Value) -> MockServer {
        let server = MockServer::start().await;
        mount_legacy(&server, endpoint, data).await;
        server
    }

    async fn serving_integration(resource: &str, data: serde_json::Value) -> MockServer {
        let server = MockServer::start().await;
        mount_site_discovery(&server).await;
        Mock::given(method("GET"))
            .and(path_regex(format!(
                r"/proxy/network/integration/v1/sites/.*/{resource}"
            )))
            .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
                "offset": 0, "limit": 200, "count": 1, "totalCount": 1,
                "data": data
            })))
            .mount(&server)
            .await;
        server
    }

    fn one_station() -> serde_json::Value {
        serde_json::json!([{
            "_id": "1", "mac": "aa:bb:cc:dd:ee:ff", "name": "Workstation", "ip": "192.0.2.20",
            "is_wired": true, "uptime": 8000, "tx_bytes": 4096, "rx_bytes": 8192,
            "signal": -55, "essid": "HomeWiFi", "ap_mac": "aa:bb:cc:dd:06:43",
            "network": "LAN", "vlan": 10, "blocked": false
        }])
    }

    fn one_switch_with_a_port() -> serde_json::Value {
        serde_json::json!([{
            "mac": "aa:bb:cc:dd:06:43", "name": "Switch Lite 8 PoE",
            "port_table": [{
                "port_idx": 1, "name": "office", "media": "GE", "up": true,
                "speed": 1000, "full_duplex": true, "port_poe": true,
                "poe_enable": true, "poe_power": 3.1,
                "tx_bytes": 100, "rx_bytes": 200,
                "last_connection": {"mac": "aabbccddeeff", "connected": true}
            }]
        }])
    }

    #[tokio::test]
    async fn clients_list_json_matches_schema_output_fields() {
        let server = serving_integration(
            "clients",
            serde_json::json!([{
                "macAddress": "aa:bb:cc:dd:ee:ff", "ipAddress": "192.0.2.20",
                "name": "Workstation", "type": "WIRED"
            }]),
        )
        .await;
        // The listing draws on both APIs: the Integration one for the roster,
        // the legacy one for the signal and traffic columns.
        mount_legacy(&server, "stat/sta", one_station()).await;
        let body = run_json(&server, &["clients", "list"]).await;
        assert_schema_matches("clients list", &body);
    }

    #[tokio::test]
    async fn clients_show_json_matches_schema_output_fields() {
        let server = serving_legacy("stat/sta", one_station()).await;
        let body = run_json(&server, &["clients", "show", "aa:bb:cc:dd:ee:ff"]).await;
        assert_schema_matches("clients show", &body);
    }

    #[tokio::test]
    async fn clients_top_json_matches_schema_output_fields() {
        let server = serving_legacy("stat/sta", one_station()).await;
        let body = run_json(&server, &["clients", "top"]).await;
        assert_schema_matches("clients top", &body);
    }

    #[tokio::test]
    async fn devices_list_json_matches_schema_output_fields() {
        let server = serving_integration(
            "devices",
            serde_json::json!([{
                "macAddress": "aa:bb:cc:dd:06:43", "ipAddress": "192.0.2.10",
                "name": "Switch Lite 8 PoE", "model": "USL8LP",
                "state": "ONLINE", "firmwareVersion": "7.1.20.16850"
            }]),
        )
        .await;
        let body = run_json(&server, &["devices", "list"]).await;
        assert_schema_matches("devices list", &body);
    }

    #[tokio::test]
    async fn networks_list_json_matches_schema_output_fields() {
        let server = serving_integration(
            "networks",
            serde_json::json!([{"name": "LAN", "vlanId": 10, "enabled": true, "default": true}]),
        )
        .await;
        let body = run_json(&server, &["networks", "list"]).await;
        assert_schema_matches("networks list", &body);
    }

    #[tokio::test]
    async fn devices_ports_json_matches_schema_output_fields() {
        let server = serving_legacy("stat/device", one_switch_with_a_port()).await;
        let body = run_json(&server, &["devices", "ports", "aa:bb:cc:dd:06:43"]).await;
        assert_schema_matches("devices ports", &body);
    }

    #[tokio::test]
    async fn ports_list_json_matches_schema_output_fields() {
        let server = serving_legacy("stat/device", one_switch_with_a_port()).await;
        let body = run_json(&server, &["ports", "list", "aa:bb:cc:dd:06:43"]).await;
        assert_schema_matches("ports list", &body);
    }

    #[tokio::test]
    async fn ports_find_json_matches_schema_output_fields() {
        let server = serving_legacy("stat/device", one_switch_with_a_port()).await;
        // `find` resolves a client to the port it is attached to, so it needs
        // the client roster as well as the port tables.
        mount_legacy(&server, "stat/sta", one_station()).await;
        let body = run_json(&server, &["ports", "find", "Workstation"]).await;
        assert_schema_matches("ports find", &body);
    }

    #[tokio::test]
    async fn events_list_json_matches_schema_output_fields() {
        let server = serving_legacy(
            "stat/event",
            serde_json::json!([{
                "key": "EVT_WU_Connected", "msg": "User connected",
                "subsystem": "wlan", "time": 1700000000,
                "datetime": "2024-01-15T10:30:00Z"
            }]),
        )
        .await;
        let body = run_json(&server, &["events", "list"]).await;
        assert_schema_matches("events list", &body);
    }

    #[tokio::test]
    async fn system_health_json_matches_schema_output_fields() {
        let server = serving_legacy(
            "stat/health",
            serde_json::json!([{
                "subsystem": "wan", "status": "ok", "num_sta": 12, "num_ap": 3,
                "num_sw": 2, "wan_ip": "203.0.113.4", "isp_name": "Example ISP"
            }]),
        )
        .await;
        let body = run_json(&server, &["system", "health"]).await;
        assert_schema_matches("system health", &body);
    }
}