cufflink-cli 0.20.0

CLI for the Cufflink CRUD microservice platform — deploy, init, and manage services
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
use clap::{CommandFactory, FromArgMatches, Parser, Subcommand};

mod commands;
mod config;
mod credentials;
mod github;
mod package_manifest;
mod pnpm;
mod project_config;
mod workspace_config;

#[derive(Parser)]
#[command(
    name = "cufflink",
    about = "Cufflink CLI — Deploy CRUD microservices in seconds",
    subcommand_required = false,
    arg_required_else_help = true
)]
struct Cli {
    /// Target environment (from Cufflink.toml)
    #[arg(short, long, global = true)]
    env: Option<String>,

    /// Print the CLI's version, and with --env the platform's and what it supports
    #[arg(short = 'V', long)]
    version: bool,

    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Initialize a new cufflink service project
    Init {
        /// Service name
        name: String,
        /// Template to use (todo, blog, ecommerce, cms)
        #[arg(short, long)]
        template: Option<String>,
        /// Service mode: crud (default) or wasm
        #[arg(short, long, default_value = "crud")]
        mode: String,
        /// Initialize from a GitHub starter kit (e.g., github:owner/repo)
        #[arg(long)]
        from: Option<String>,
    },
    /// List available service templates
    Templates,
    /// Install a package from GitHub or local path
    Install {
        /// Package source (e.g., github:owner/repo, github:owner/repo@v1.0.0, or /local/path)
        source: String,
    },
    /// Deploy all components in an installed package
    DeployPackage {
        /// Package name (as listed in cufflink-packages/)
        name: String,
        /// Skip specific components by name (repeatable)
        #[arg(long, value_delimiter = ',')]
        skip: Option<Vec<String>>,
    },
    /// Deploy a service to the platform
    Deploy {
        /// Allow destructive schema changes
        #[arg(long)]
        allow_destructive: bool,
        /// Under an enforced schema guard, leave what the database
        /// contradicts as it is and deploy the rest
        #[arg(long)]
        accept_drift: bool,
        /// Under an enforced schema guard, drop the tables and columns the
        /// deploy removes instead of archiving them
        #[arg(long)]
        purge: bool,
        /// Print what the deploy would do (schema changes, migrations, what
        /// the guard found) and deploy nothing; exits 3 when the platform
        /// refuses the deploy (422), 1 when the plan could not be made
        #[arg(long)]
        plan: bool,
        /// Git commit hash to associate with this deployment (auto-detected if omitted)
        #[arg(long)]
        commit_hash: Option<String>,
        /// Deploy to a specific tenant (overrides Cufflink.toml)
        #[arg(long)]
        tenant: Option<String>,
    },
    /// Rollback to a previous deployment version
    Rollback {
        /// Target version (defaults to previous)
        #[arg(short, long)]
        version: Option<i32>,
        /// Allow destructive schema changes (dropping tables/columns)
        #[arg(long)]
        allow_destructive: bool,
    },
    /// Show service status
    Status,
    /// Stream service logs
    Logs {
        /// Follow log output in real-time
        #[arg(short, long)]
        follow: bool,
        /// Show logs from this duration ago (e.g., 1h, 30m, 24h)
        #[arg(long)]
        since: Option<String>,
        /// Start time (RFC3339)
        #[arg(long)]
        from: Option<String>,
        /// End time (RFC3339)
        #[arg(long)]
        to: Option<String>,
        /// Filter logs containing this text
        #[arg(short, long)]
        search: Option<String>,
        /// Filter by log level (debug, info, warn, error)
        #[arg(short, long)]
        level: Option<String>,
        /// Maximum number of log lines (default: 100)
        #[arg(short = 'n', long)]
        limit: Option<usize>,
        /// Save logs to a file
        #[arg(short, long)]
        output: Option<String>,
    },
    /// Manage API keys (list, revoke, rotate)
    Auth {
        #[command(subcommand)]
        action: commands::auth::AuthAction,
    },
    /// Manage partner keys for `api_key` routes
    Keys {
        #[command(subcommand)]
        action: commands::keys::KeysAction,
    },
    /// List all deployed services
    Services {
        #[command(subcommand)]
        action: Option<ServicesAction>,
    },
    /// Audit custom-route authorization postures (local service, or all deployed)
    Routes {
        /// Audit every deployed service instead of the local one
        #[arg(long)]
        all_services: bool,
        /// Exit non-zero if any anonymous or undeclared route is found
        #[arg(long)]
        audit: bool,
    },
    /// Inspect and clean up deployment history for the current service
    Deployments {
        #[command(subcommand)]
        action: DeploymentsAction,
    },
    /// The durable consumers of the current service
    Consumers {
        #[command(subcommand)]
        action: ConsumersAction,
    },
    /// A platform on this machine to develop against
    Dev {
        #[command(subcommand)]
        action: commands::dev::DevAction,
    },
    /// The tenant's dead-letter queue: what its consumers gave up on
    Dlq {
        #[command(subcommand)]
        action: DlqAction,
    },
    /// Print or save the OpenAPI spec for the current service
    Openapi {
        /// Write spec to a file instead of stdout
        #[arg(short, long)]
        output: Option<String>,
        /// Generate locally from the manifest (no deployment required)
        #[arg(long)]
        local: bool,
        /// Tenant slug for URL paths (used with --local, default: "local")
        #[arg(long)]
        tenant_slug: Option<String>,
    },
    /// Generate a TypeScript client from the OpenAPI spec
    GenerateClient(commands::openapi::GenerateClientArgs),
    /// Platform administration (platform admin only)
    Admin {
        /// Platform API URL (overrides Cufflink.toml and CUFFLINK_API_URL)
        #[arg(long)]
        api_url: Option<String>,
        #[command(subcommand)]
        action: commands::admin::AdminAction,
    },
    /// The extensions a tenant registers (platform admin only)
    Ext {
        /// Platform API URL (overrides Cufflink.toml and CUFFLINK_API_URL)
        #[arg(long)]
        api_url: Option<String>,
        #[command(subcommand)]
        action: commands::ext::ExtAction,
    },
    /// Manage tenants (platform admin only)
    Tenants {
        /// Platform API URL (overrides Cufflink.toml and CUFFLINK_API_URL)
        #[arg(long)]
        api_url: Option<String>,
        #[command(subcommand)]
        action: TenantsAction,
    },
    /// Authenticate with the platform
    Login,
    /// Run tests (hash-based, only changed)
    Test {
        /// Run all tests regardless of hash
        #[arg(long)]
        all: bool,
    },
    /// Seed data into a deployed service from a JSON file
    Seed {
        /// Path to seed JSON file (default: seed.json)
        #[arg(default_value = "seed.json")]
        file: String,
        /// Clear existing data before seeding
        #[arg(long)]
        clear: bool,
        /// Only seed specific tables (comma-separated)
        #[arg(long, value_delimiter = ',')]
        tables: Option<Vec<String>>,
    },
    /// Manage service configuration
    Config {
        #[command(subcommand)]
        action: ConfigAction,
    },
    /// Backup and restore service data
    Backup {
        #[command(subcommand)]
        action: BackupAction,
    },
    /// Manage long-running jobs
    Jobs {
        #[command(subcommand)]
        action: JobsAction,
    },
    /// Workspace-wide deploy, test, seed, and status
    Workspace {
        #[command(subcommand)]
        action: WorkspaceAction,
    },
    /// Generate CI/CD pipeline configuration
    Ci {
        #[command(subcommand)]
        action: CiAction,
    },
    /// Manage roles and role assignments
    Roles {
        #[command(subcommand)]
        action: RolesAction,
    },
    /// Manage encrypted secrets (securestore)
    Secrets {
        #[command(subcommand)]
        action: SecretsAction,
    },
    /// Run a read-only SQL query against a service's tenant database
    Sql {
        /// SQL query string
        query: String,
        /// Service name (defaults to current service if run inside one)
        #[arg(long)]
        service: Option<String>,
        /// Tenant slug override (defaults to tenant from Cufflink.toml for --env)
        #[arg(long)]
        tenant: Option<String>,
        /// Output format: table (default), jsonl, csv, tsv
        #[arg(long)]
        format: Option<String>,
        /// Render/display all rows (default truncates to 1000 in TTY mode). TTY + --all auto-pages.
        #[arg(long)]
        all: bool,
        /// Row cap of one SELECT, WITH, VALUES or TABLE query that writes
        /// nothing, applied as `SELECT * FROM (<query>) q LIMIT N`; anything
        /// else is sent as typed. The server still enforces its own max.
        #[arg(long)]
        limit: Option<u64>,
        /// Disable the auto-pager when rendering large tables on a TTY.
        #[arg(long)]
        no_pager: bool,
    },
}

#[derive(Subcommand)]
enum ConfigAction {
    /// List all config values
    List,
    /// Set a config value
    Set {
        /// Config key
        key: String,
        /// Config value
        value: String,
        /// Mark as secret (value masked in API responses)
        #[arg(long)]
        secret: bool,
    },
    /// Delete a config value
    Delete {
        /// Config key to delete
        key: String,
    },
    /// Sync configs and secrets from Cufflink.toml to the platform
    Sync,
}

#[derive(Subcommand)]
enum SecretsAction {
    /// Initialize a new secrets vault for an environment
    Init,
    /// Initialize empty vaults in the current service using another workspace service's keys
    InitFrom {
        /// Name of the sibling service to copy key files from (must appear in cufflink-workspace.toml)
        #[arg(long)]
        from: String,
        /// Limit to a single environment (e.g., staging). If omitted, all envs with a key in the source are copied.
        #[arg(long)]
        store: Option<String>,
    },
    /// Re-encrypt existing vaults in the current service using another service's keys
    Rekey {
        /// Name of the sibling service whose key(s) should become the new encryption key
        #[arg(long)]
        from: String,
        /// Limit to a single environment. If omitted, every local vault with a matching source key is rekeyed.
        #[arg(long)]
        store: Option<String>,
    },
    /// Set a secret value
    Set {
        /// Secret name (e.g., "keycloak:client_secret")
        name: String,
        /// Secret value
        value: String,
    },
    /// List secret names (values are not shown unless --reveal is used)
    List {
        /// Show secret values
        #[arg(long)]
        reveal: bool,
    },
    /// Delete a secret from the vault
    Delete {
        /// Secret name to delete
        name: String,
    },
}

#[derive(Subcommand)]
enum ConsumersAction {
    /// List the durables the manifest wants, what the server has of each,
    /// and the handovers on record
    Ls,
}

#[derive(Subcommand)]
enum DlqAction {
    /// List the newest dead letters
    Ls {
        /// Only the letters of this service
        #[arg(long)]
        service: Option<String>,
        /// How many to show (at most 200)
        #[arg(short = 'n', long)]
        limit: Option<usize>,
    },
    /// Publish a dead letter again where it came from, then drop it
    Replay {
        /// The letter's sequence in the queue
        sequence: u64,
    },
    /// Drop a dead letter
    Drop {
        /// The letter's sequence in the queue
        sequence: u64,
    },
}

#[derive(Subcommand)]
enum DeploymentsAction {
    /// List deployment history for the current service
    List {
        /// Show only the most recent N deployments
        #[arg(short = 'n', long)]
        limit: Option<usize>,
    },
    /// Delete oldest deployments, retaining the N most recent (current always kept)
    Prune {
        /// Number of recent deployments to retain (>= 1)
        #[arg(long)]
        keep: usize,
        /// Skip confirmation prompt
        #[arg(long)]
        yes: bool,
    },
    /// Delete a single deployment by version (cannot delete the active version)
    Delete {
        /// Deployment version to remove
        version: i32,
        /// Skip confirmation prompt
        #[arg(long)]
        yes: bool,
    },
}

#[derive(Subcommand)]
enum ServicesAction {
    /// List deployed services
    List {
        /// Also show each service's required platform features
        #[arg(long)]
        features: bool,
    },
    /// Delete a deployed service and all its data (a native service as a
    /// platform admin, with CUFFLINK_PLATFORM_API_KEY)
    Delete {
        /// Service name to delete
        name: String,
        /// Skip confirmation prompt
        #[arg(long)]
        yes: bool,
        /// Delete a native service even while a deployed service calls one
        /// of its extensions
        #[arg(long)]
        force: bool,
    },
    /// The database role a service runs as (platform admin only)
    DbRole {
        /// Platform API URL (overrides Cufflink.toml and CUFFLINK_API_URL)
        #[arg(long)]
        api_url: Option<String>,
        #[command(subcommand)]
        action: commands::db_role::DbRoleAction,
    },
    /// Enable a service (make it active and routable; a native service as a
    /// platform admin)
    Enable {
        /// Service name
        name: String,
    },
    /// Disable a service (make it inactive — stops routing traffic; a
    /// native service as a platform admin)
    Disable {
        /// Service name
        name: String,
    },
}

#[derive(Subcommand)]
enum JobsAction {
    /// Give a failed job one more attempt
    Retry {
        /// The job's id
        job_id: uuid::Uuid,
    },
}

#[derive(Subcommand)]
enum BackupAction {
    /// Show service tables, columns, and FK dependencies
    Schema,
    /// Export service data to a file
    Export {
        /// Output file path
        #[arg(short, long, default_value = "backup.jsonl")]
        output: String,
        /// Export only specific tables (comma-separated)
        #[arg(long, value_delimiter = ',')]
        tables: Option<Vec<String>>,
        /// Return job ID immediately without waiting
        #[arg(long, rename_all = "kebab-case")]
        r#async: bool,
    },
    /// Restore service data from a file or a previous backup
    Restore {
        /// Input file path (optional if --from-backup is used)
        file: Option<String>,
        /// Restore directly from a previous backup job ID (skip local file)
        #[arg(long)]
        from_backup: Option<String>,
        /// Restore only specific tables (comma-separated)
        #[arg(long, value_delimiter = ',')]
        tables: Option<Vec<String>>,
        /// Clear existing data before restoring
        #[arg(long)]
        clear: bool,
        /// Skip schema and FK validation checks
        #[arg(long)]
        force: bool,
        /// Return job ID immediately without waiting
        #[arg(long, rename_all = "kebab-case")]
        r#async: bool,
    },
    /// List completed backups available for restore
    List,
    /// List all backup/restore jobs (including in-progress and failed)
    Jobs,
    /// Cancel a running backup/restore job
    Cancel {
        /// Job ID to cancel
        job_id: String,
    },
}

#[derive(Subcommand)]
enum WorkspaceAction {
    /// Deploy all services for the current environment
    Deploy {
        /// Skip specific services (comma-separated)
        #[arg(long, value_delimiter = ',')]
        skip: Option<Vec<String>>,
        /// Deploy to a specific tenant (overrides Cufflink.toml)
        #[arg(long)]
        tenant: Option<String>,
        /// Deploy services in parallel
        #[arg(long)]
        parallel: bool,
    },
    /// Run tests for all services
    Test {
        /// Skip specific services (comma-separated)
        #[arg(long, value_delimiter = ',')]
        skip: Option<Vec<String>>,
        /// Show full test output
        #[arg(long)]
        all: bool,
    },
    /// Show deploy status of all services
    Status,
    /// Seed data for configured services
    Seed,
    /// Create or destroy a preview environment
    Preview {
        #[command(subcommand)]
        action: PreviewAction,
    },
}

#[derive(Subcommand)]
enum PreviewAction {
    /// Create a preview environment (new tenant + deploy + clone data)
    Create {
        /// Preview name (used as tenant slug: preview-<name>)
        #[arg(long)]
        name: String,
        /// Source tenant to clone data from
        #[arg(long, default_value = "default")]
        source_tenant: String,
    },
    /// Destroy a preview environment
    Destroy {
        /// Preview name
        #[arg(long)]
        name: String,
    },
}

#[derive(Subcommand)]
enum CiAction {
    /// Generate GitHub Actions workflow for deploy pipeline
    Init {
        /// CI provider (github)
        #[arg(long, default_value = "github")]
        provider: String,
    },
}

#[derive(Subcommand)]
enum TenantsAction {
    /// Create a new tenant
    Create {
        /// Tenant display name
        #[arg(long)]
        name: String,
        /// Tenant slug (URL-safe identifier)
        #[arg(long)]
        slug: String,
        /// Keycloak URL for this tenant's realm
        #[arg(long)]
        tenant_keycloak_url: Option<String>,
        /// Keycloak realm name for this tenant
        #[arg(long)]
        tenant_keycloak_realm: Option<String>,
        /// Required Keycloak realm role for deploy access (default: cufflink-deploy)
        #[arg(long)]
        deploy_role: Option<String>,
        /// An existing database the tenant adopts; the platform never
        /// creates or drops it, and it cannot be changed afterwards
        #[arg(long)]
        database_name: Option<String>,
    },
    /// Update a tenant's configuration
    Update {
        /// Tenant slug to update
        slug: String,
        /// New display name
        #[arg(long)]
        name: Option<String>,
        /// Keycloak URL for this tenant's realm
        #[arg(long)]
        tenant_keycloak_url: Option<String>,
        /// Keycloak realm name for this tenant
        #[arg(long)]
        tenant_keycloak_realm: Option<String>,
        /// Required Keycloak realm role for deploy access
        #[arg(long)]
        deploy_role: Option<String>,
        /// Keycloak client ID for admin API operations (user search)
        #[arg(long)]
        keycloak_ops_client_id: Option<String>,
        /// Keycloak client secret for admin API operations (user search)
        #[arg(long)]
        keycloak_ops_client_secret: Option<String>,
        /// Comma-separated Keycloak client ids treated as service accounts on
        /// this tenant; an empty value clears the list
        #[arg(long)]
        service_account_clients: Option<String>,
        /// Browser-facing Keycloak base URL this tenant's tokens are issued
        /// under, when it differs from the platform's; an empty value clears it
        #[arg(long)]
        keycloak_issuer: Option<String>,
    },
    /// Show or change a tenant's policies
    Policy {
        #[command(subcommand)]
        action: PolicyAction,
    },
    /// Show or replace the NATS subjects and streams a tenant claims
    /// beyond its own
    NatsClaims {
        #[command(subcommand)]
        action: NatsClaimsAction,
    },
    /// Create, list or revoke the keys a tenant's runners (its extension
    /// runner and a tenant-scoped web runner) authenticate with
    RunnerKeys {
        #[command(subcommand)]
        action: commands::runner_keys::RunnerKeysAction,
    },
    /// List all tenants
    List,
    /// Delete a tenant and all its data
    Delete {
        /// Tenant slug to delete
        slug: String,
        /// Skip confirmation prompt
        #[arg(long)]
        yes: bool,
    },
    /// Create a platform admin API key
    CreateApiKey {
        /// Key name (for identification)
        #[arg(long)]
        name: String,
    },
    /// List platform admin API keys
    ListApiKeys,
    /// Revoke a platform admin API key
    RevokeApiKey {
        /// API key ID to revoke
        id: String,
    },
}

#[derive(Subcommand)]
enum NatsClaimsAction {
    /// Show the tenant's claims
    Show {
        /// Tenant slug
        slug: String,
    },
    /// Replace the tenant's claims with the ones given
    Set {
        /// Tenant slug
        slug: String,
        /// A subject pattern the tenant claims (repeatable)
        #[arg(
            long = "subject",
            required_unless_present_any = ["streams", "clear"]
        )]
        subjects: Vec<String>,
        /// A stream the tenant claims (repeatable)
        #[arg(long = "stream")]
        streams: Vec<String>,
        /// Leave the tenant with no claim
        #[arg(long, conflicts_with_all = ["subjects", "streams"])]
        clear: bool,
    },
}

#[derive(Subcommand)]
enum PolicyAction {
    /// Show every policy's mode, config and whether it is the tenant's own
    Get {
        /// Tenant slug
        slug: String,
    },
    /// Set a policy's mode (and optionally its config) for a tenant
    Set {
        /// Tenant slug
        slug: String,
        /// Policy key (tenant_binding, graphql, storage_scope, egress,
        /// wasm_limits, service_accounts, audience, redis_scope, strict_filters,
        /// outbox, db_roles, schema_guard)
        key: cufflink_types::policy::PolicyKey,
        /// off, warn or enforce
        mode: cufflink_types::policy::PolicyMode,
        /// Policy config as JSON; omitted keeps the current config
        #[arg(long, value_parser = parse_json)]
        config: Option<serde_json::Value>,
    },
    /// Drop the tenant's own setting, returning to the platform default
    Reset {
        /// Tenant slug
        slug: String,
        /// Policy key
        key: cufflink_types::policy::PolicyKey,
    },
}

fn parse_json(raw: &str) -> Result<serde_json::Value, String> {
    serde_json::from_str(raw).map_err(|e| format!("not valid JSON: {e}"))
}

#[derive(Subcommand)]
enum RolesAction {
    /// List all roles and their permissions
    List,
    /// Assign a role to a user
    Assign {
        /// User email or username to search for
        #[arg(long)]
        user: String,
        /// Role name to assign
        #[arg(long)]
        role: String,
    },
    /// Remove a role from a user
    Unassign {
        /// User email or username to search for
        #[arg(long)]
        user: String,
        /// Role name to remove
        #[arg(long)]
        role: String,
    },
}

#[tokio::main]
async fn main() -> std::process::ExitCode {
    run().await.map_or_else(
        |error| {
            eprintln!("Error: {error:?}");
            std::process::ExitCode::from(exit_code(&error))
        },
        |()| std::process::ExitCode::SUCCESS,
    )
}

/// 3 for a plan the platform refused, 1 for any other failure.
fn exit_code(error: &eyre::Report) -> u8 {
    error
        .downcast_ref::<commands::deploy::Refused>()
        .map_or(1, |_| commands::deploy::Refused::EXIT_CODE)
}

async fn run() -> eyre::Result<()> {
    let matches = Cli::command().get_matches();
    if matches.get_flag("version") {
        return commands::version::print(matches.get_one::<String>("env").map(String::as_str))
            .await;
    }
    let cli = Cli::from_arg_matches(&matches)
        .unwrap_or_else(|error| error.format(&mut Cli::command()).exit());
    let env = cli.env.as_deref();

    match cli.command {
        Commands::Init {
            name,
            template,
            mode,
            from,
        } => {
            commands::init::run(&name, template.as_deref(), &mode, from.as_deref()).await?;
        }
        Commands::Install { source } => {
            commands::install::run(&source).await?;
        }
        Commands::DeployPackage { name, skip } => {
            let skip_list = skip.unwrap_or_default();
            commands::deploy_package::run(&name, &skip_list, env).await?;
        }
        Commands::Templates => {
            commands::init::list_templates();
        }
        Commands::Deploy {
            allow_destructive,
            accept_drift,
            purge,
            plan,
            commit_hash,
            tenant,
        } => {
            let flags = commands::deploy::DeployFlags {
                allow_destructive,
                accept_drift,
                purge,
                plan,
            };
            commands::deploy::run_with(flags, commit_hash, env, tenant.as_deref()).await?;
        }
        Commands::Rollback {
            version,
            allow_destructive,
        } => {
            commands::rollback::run(version, allow_destructive, env).await?;
        }
        Commands::Status => {
            commands::status::run(env).await?;
        }
        Commands::Logs {
            follow,
            since,
            from,
            to,
            search,
            level,
            limit,
            output,
        } => {
            commands::logs::run(
                commands::logs::LogParams {
                    follow,
                    since: since.as_deref(),
                    from: from.as_deref(),
                    to: to.as_deref(),
                    search: search.as_deref(),
                    level: level.as_deref(),
                    limit,
                    output: output.as_deref(),
                },
                env,
            )
            .await?;
        }
        Commands::Auth { action } => commands::auth::run(action, env).await?,
        Commands::Keys { action } => commands::keys::run(action, env).await?,
        Commands::Services { action } => match action {
            None => commands::services::run(false, env).await?,
            Some(ServicesAction::List { features }) => {
                commands::services::run(features, env).await?
            }
            Some(ServicesAction::Delete { name, yes, force }) => {
                commands::services::delete(&name, yes, force, env).await?
            }
            Some(ServicesAction::DbRole { api_url, action }) => {
                commands::db_role::run(action, api_url.as_deref(), env).await?
            }
            Some(ServicesAction::Enable { name }) => {
                commands::services::set_status(&name, "active", env).await?
            }
            Some(ServicesAction::Disable { name }) => {
                commands::services::set_status(&name, "inactive", env).await?
            }
        },
        Commands::Routes {
            all_services,
            audit,
        } => commands::routes::run(all_services, audit, env).await?,
        Commands::Consumers { action } => match action {
            ConsumersAction::Ls => commands::consumers::ls(env).await?,
        },
        Commands::Dev { action } => commands::dev::run(action).await?,
        Commands::Dlq { action } => match action {
            DlqAction::Ls { service, limit } => {
                commands::dlq::ls(service.as_deref(), limit, env).await?
            }
            DlqAction::Replay { sequence } => commands::dlq::replay(sequence, env).await?,
            DlqAction::Drop { sequence } => commands::dlq::drop(sequence, env).await?,
        },
        Commands::Deployments { action } => match action {
            DeploymentsAction::List { limit } => commands::deployments::list(limit, env).await?,
            DeploymentsAction::Prune { keep, yes } => {
                commands::deployments::prune(keep, yes, env).await?
            }
            DeploymentsAction::Delete { version, yes } => {
                commands::deployments::delete(version, yes, env).await?
            }
        },
        Commands::Openapi {
            output,
            local,
            tenant_slug,
        } => {
            if let Some(path) = output {
                commands::openapi::save(&path, local, tenant_slug.as_deref(), env).await?;
            } else {
                commands::openapi::run(local, tenant_slug.as_deref(), env).await?;
            }
        }
        Commands::GenerateClient(args) => {
            commands::openapi::generate_client(&args, env).await?;
        }
        Commands::Admin { action, api_url } => {
            commands::admin::run(action, api_url.as_deref(), env).await?
        }
        Commands::Ext { action, api_url } => {
            commands::ext::run(action, api_url.as_deref(), env).await?
        }
        Commands::Tenants { action, api_url } => match action {
            TenantsAction::Create {
                name,
                slug,
                tenant_keycloak_url,
                tenant_keycloak_realm,
                deploy_role,
                database_name,
            } => {
                commands::tenants::create(
                    &commands::tenants::NewTenant {
                        name: &name,
                        slug: &slug,
                        keycloak_url: tenant_keycloak_url.as_deref(),
                        keycloak_realm: tenant_keycloak_realm.as_deref(),
                        deploy_role: deploy_role.as_deref(),
                        database_name: database_name.as_deref(),
                    },
                    api_url.as_deref(),
                    env,
                )
                .await?
            }
            TenantsAction::Update {
                slug,
                name,
                tenant_keycloak_url,
                tenant_keycloak_realm,
                deploy_role,
                keycloak_ops_client_id,
                keycloak_ops_client_secret,
                service_account_clients,
                keycloak_issuer,
            } => {
                let changes = commands::tenants::TenantChanges {
                    name: name.as_deref(),
                    keycloak_url: tenant_keycloak_url.as_deref(),
                    keycloak_realm: tenant_keycloak_realm.as_deref(),
                    deploy_role: deploy_role.as_deref(),
                    keycloak_ops_client_id: keycloak_ops_client_id.as_deref(),
                    keycloak_ops_client_secret: keycloak_ops_client_secret.as_deref(),
                    service_account_clients: service_account_clients.as_deref(),
                    keycloak_issuer: keycloak_issuer.as_deref(),
                };
                commands::tenants::update(&slug, &changes, api_url.as_deref(), env).await?
            }
            TenantsAction::Policy { action } => match action {
                PolicyAction::Get { slug } => {
                    commands::tenants::policy_get(&slug, api_url.as_deref(), env).await?
                }
                PolicyAction::Set {
                    slug,
                    key,
                    mode,
                    config,
                } => {
                    commands::tenants::policy_set(&slug, key, mode, config, api_url.as_deref(), env)
                        .await?
                }
                PolicyAction::Reset { slug, key } => {
                    commands::tenants::policy_reset(&slug, key, api_url.as_deref(), env).await?
                }
            },
            TenantsAction::NatsClaims { action } => match action {
                NatsClaimsAction::Show { slug } => {
                    commands::tenants::nats_claims_show(&slug, api_url.as_deref(), env).await?
                }
                NatsClaimsAction::Set {
                    slug,
                    subjects,
                    streams,
                    ..
                } => {
                    commands::tenants::nats_claims_set(
                        &slug,
                        &subjects,
                        &streams,
                        api_url.as_deref(),
                        env,
                    )
                    .await?
                }
            },
            TenantsAction::RunnerKeys { action } => {
                commands::runner_keys::run(action, api_url.as_deref(), env).await?
            }
            TenantsAction::List => commands::tenants::list(api_url.as_deref(), env).await?,
            TenantsAction::Delete { slug, yes } => {
                commands::tenants::delete(&slug, yes, api_url.as_deref(), env).await?
            }
            TenantsAction::CreateApiKey { name } => {
                commands::tenants::create_platform_api_key(&name, api_url.as_deref(), env).await?
            }
            TenantsAction::ListApiKeys => {
                commands::tenants::list_platform_api_keys(api_url.as_deref(), env).await?
            }
            TenantsAction::RevokeApiKey { id } => {
                commands::tenants::revoke_platform_api_key(&id, api_url.as_deref(), env).await?
            }
        },
        Commands::Login => {
            commands::login::run(env).await?;
        }
        Commands::Test { all } => {
            commands::test::run(all, env).await?;
        }
        Commands::Seed {
            file,
            clear,
            tables,
        } => {
            commands::seed::run(&file, clear, tables, env).await?;
        }
        Commands::Config { action } => match action {
            ConfigAction::List => commands::config_cmd::list(env).await?,
            ConfigAction::Set { key, value, secret } => {
                commands::config_cmd::set(&key, &value, secret, env).await?
            }
            ConfigAction::Delete { key } => commands::config_cmd::delete(&key, env).await?,
            ConfigAction::Sync => commands::config_cmd::sync(env).await?,
        },
        Commands::Jobs { action } => match action {
            JobsAction::Retry { job_id } => commands::jobs::retry(job_id, env).await?,
        },
        Commands::Backup { action } => match action {
            BackupAction::Schema => commands::backup::schema(env).await?,
            BackupAction::Export {
                output,
                tables,
                r#async,
            } => commands::backup::export(&output, tables, r#async, env).await?,
            BackupAction::Restore {
                file,
                from_backup,
                tables,
                clear,
                force,
                r#async,
            } => {
                commands::backup::restore(
                    file.as_deref(),
                    from_backup.as_deref(),
                    tables,
                    clear,
                    force,
                    r#async,
                    env,
                )
                .await?
            }
            BackupAction::List => commands::backup::list(env).await?,
            BackupAction::Jobs => commands::backup::jobs(env).await?,
            BackupAction::Cancel { job_id } => commands::backup::cancel(&job_id, env).await?,
        },
        Commands::Workspace { action } => match action {
            WorkspaceAction::Deploy {
                skip,
                tenant,
                parallel,
            } => {
                let skip_list = skip.unwrap_or_default();
                commands::workspace::deploy(&skip_list, env, tenant.as_deref(), parallel).await?
            }
            WorkspaceAction::Test { skip, all } => {
                let skip_list = skip.unwrap_or_default();
                commands::workspace::test(&skip_list, all).await?
            }
            WorkspaceAction::Status => commands::workspace::status(env).await?,
            WorkspaceAction::Seed => commands::workspace::seed(env).await?,
            WorkspaceAction::Preview { action } => match action {
                PreviewAction::Create {
                    name,
                    source_tenant,
                } => commands::workspace::preview_create(&name, &source_tenant, env).await?,
                PreviewAction::Destroy { name } => {
                    commands::workspace::preview_destroy(&name, env).await?
                }
            },
        },
        Commands::Ci { action } => match action {
            CiAction::Init { provider } => commands::ci::init(&provider)?,
        },
        Commands::Secrets { action } => match action {
            SecretsAction::Init => commands::secrets_cmd::init(env)?,
            SecretsAction::InitFrom { from, store } => {
                commands::secrets_cmd::init_from(&from, store.as_deref(), env)?
            }
            SecretsAction::Rekey { from, store } => {
                commands::secrets_cmd::rekey(&from, store.as_deref(), env)?
            }
            SecretsAction::Set { name, value } => commands::secrets_cmd::set(&name, &value, env)?,
            SecretsAction::List { reveal } => commands::secrets_cmd::list(env, reveal)?,
            SecretsAction::Delete { name } => commands::secrets_cmd::delete(&name, env)?,
        },
        Commands::Sql {
            query,
            service,
            tenant,
            format,
            all,
            limit,
            no_pager,
        } => {
            commands::sql::run(
                &query,
                service.as_deref(),
                tenant.as_deref(),
                format.as_deref(),
                all,
                limit,
                no_pager,
                env,
            )
            .await?
        }
        Commands::Roles { action } => match action {
            RolesAction::List => commands::roles::list(env).await?,
            RolesAction::Assign { user, role } => {
                commands::roles::assign(&user, &role, env).await?
            }
            RolesAction::Unassign { user, role } => {
                commands::roles::unassign(&user, &role, env).await?
            }
        },
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use cufflink_types::policy::{PolicyKey, PolicyMode};

    #[test]
    fn the_version_is_asked_for_with_or_without_an_environment() {
        Cli::command().debug_assert();
        let asked = |argv: &[&str]| {
            Cli::command()
                .try_get_matches_from(argv)
                .map(|matches| {
                    (
                        matches.get_flag("version"),
                        matches.get_one::<String>("env").cloned(),
                    )
                })
                .ok()
        };
        assert_eq!(asked(&["cufflink", "--version"]), Some((true, None)));
        assert_eq!(
            asked(&["cufflink", "-V", "--env", "dev"]),
            Some((true, Some("dev".to_string())))
        );
        assert!(Cli::try_parse_from(["cufflink", "--env", "dev"]).is_err());
        assert!(Cli::try_parse_from(["cufflink"]).is_err());
        assert!(matches!(
            Cli::try_parse_from(["cufflink", "--env", "dev", "status"]).map(|cli| cli.command),
            Ok(Commands::Status)
        ));
    }

    #[test]
    fn the_development_stack_is_started_from_images_or_from_source() {
        use commands::dev::DevAction;
        let dev = |arguments: &[&str]| {
            Cli::try_parse_from(["cufflink", "dev"].iter().chain(arguments)).map(|cli| cli.command)
        };
        assert!(matches!(
            dev(&["up"]),
            Ok(Commands::Dev {
                action: DevAction::Up {
                    from_source: None,
                    platform_image: None,
                    worker_image: None,
                    web_runner_image: None,
                    ext_runner_image: None,
                    with_web_runner: false,
                    with_ext_runner: false,
                }
            })
        ));
        assert!(matches!(
            dev(&["up", "--platform-image", "registry.test/platform:1", "--with-web-runner"]),
            Ok(Commands::Dev {
                action: DevAction::Up {
                    platform_image: Some(image),
                    with_web_runner: true,
                    with_ext_runner: false,
                    ..
                }
            }) if image == "registry.test/platform:1"
        ));
        assert!(matches!(
            dev(&["up", "--ext-runner-image", "registry.test/ext-runner:1", "--with-ext-runner"]),
            Ok(Commands::Dev {
                action: DevAction::Up {
                    ext_runner_image: Some(image),
                    with_web_runner: false,
                    with_ext_runner: true,
                    ..
                }
            }) if image == "registry.test/ext-runner:1"
        ));
        assert!(matches!(
            dev(&["up", "--from-source", "../cufflink"]),
            Ok(Commands::Dev {
                action: DevAction::Up {
                    from_source: Some(repo),
                    ..
                }
            }) if repo == std::path::Path::new("../cufflink")
        ));
        for image in [
            "--platform-image",
            "--worker-image",
            "--web-runner-image",
            "--ext-runner-image",
        ] {
            assert!(
                dev(&["up", "--from-source", ".", image, "x"]).is_err(),
                "{image}"
            );
        }
    }

    #[test]
    fn the_development_stack_is_stopped_read_and_deployed_to() {
        use commands::dev::DevAction;
        let dev = |arguments: &[&str]| {
            Cli::try_parse_from(["cufflink", "dev"].iter().chain(arguments)).map(|cli| cli.command)
        };
        assert!(matches!(
            dev(&["down", "--volumes"]),
            Ok(Commands::Dev {
                action: DevAction::Down { volumes: true }
            })
        ));
        assert!(matches!(
            dev(&["logs", "platform", "-f"]),
            Ok(Commands::Dev {
                action: DevAction::Logs { service: Some(service), follow: true }
            }) if service == "platform"
        ));
        assert!(matches!(
            dev(&["logs"]),
            Ok(Commands::Dev {
                action: DevAction::Logs {
                    service: None,
                    follow: false
                }
            })
        ));
        assert!(matches!(
            dev(&["token", "--user", "alice"]),
            Ok(Commands::Dev {
                action: DevAction::Token { user, password: None }
            }) if user == "alice"
        ));
        assert!(dev(&["token"]).is_err());
        assert!(matches!(
            dev(&["deploy", "--watch"]),
            Ok(Commands::Dev {
                action: DevAction::Deploy { watch: true }
            })
        ));
        assert!(matches!(
            dev(&["doctor"]),
            Ok(Commands::Dev {
                action: DevAction::Doctor {
                    with_web_runner: false,
                    with_ext_runner: false
                }
            })
        ));
        assert!(matches!(
            dev(&["doctor", "--with-web-runner"]),
            Ok(Commands::Dev {
                action: DevAction::Doctor {
                    with_web_runner: true,
                    with_ext_runner: false
                }
            })
        ));
        assert!(matches!(
            dev(&["doctor", "--with-ext-runner", "--with-web-runner"]),
            Ok(Commands::Dev {
                action: DevAction::Doctor {
                    with_web_runner: true,
                    with_ext_runner: true
                }
            })
        ));
    }

    #[test]
    fn a_job_is_retried_by_its_id() {
        let retry = |id: &'static str| {
            Cli::try_parse_from(["cufflink", "jobs", "retry", id]).map(|cli| cli.command)
        };
        assert!(matches!(
            retry("97c9e5c1-3f4a-4d0f-a53a-2273c4be3aad"),
            Ok(Commands::Jobs {
                action: JobsAction::Retry { job_id }
            }) if job_id.to_string() == "97c9e5c1-3f4a-4d0f-a53a-2273c4be3aad"
        ));
        assert!(retry("not-a-job").is_err());
        assert!(Cli::try_parse_from(["cufflink", "jobs", "retry"]).is_err());
    }

    #[test]
    fn nats_claims_take_repeated_subjects_and_streams() {
        let argv = [
            "cufflink",
            "tenants",
            "nats-claims",
            "set",
            "mantis",
            "--subject",
            "leads.>",
            "--subject",
            "audit.logs",
            "--stream",
            "LEADS",
        ];
        let parsed = Cli::try_parse_from(argv).expect("parses").command;
        assert!(matches!(
            parsed,
            Commands::Tenants {
                action: TenantsAction::NatsClaims {
                    action: NatsClaimsAction::Set { slug, subjects, streams, clear }
                },
                ..
            } if slug == "mantis"
                && subjects == ["leads.>", "audit.logs"]
                && streams == ["LEADS"]
                && !clear
        ));
        let set = |flags: &[&str]| {
            Cli::try_parse_from(
                ["cufflink", "tenants", "nats-claims", "set", "mantis"]
                    .iter()
                    .chain(flags),
            )
            .map(|cli| cli.command)
        };
        assert!(matches!(
            set(&["--clear"]),
            Ok(Commands::Tenants {
                action: TenantsAction::NatsClaims {
                    action: NatsClaimsAction::Set { subjects, streams, clear, .. }
                },
                ..
            }) if subjects.is_empty() && streams.is_empty() && clear
        ));
        assert!(matches!(
            set(&["--stream", "LEADS"]),
            Ok(Commands::Tenants {
                action: TenantsAction::NatsClaims {
                    action: NatsClaimsAction::Set { subjects, streams, .. }
                },
                ..
            }) if subjects.is_empty() && streams == ["LEADS"]
        ));
        assert!(
            set(&[]).is_err(),
            "every claim is never dropped by leaving the flags out"
        );
        for both in [
            ["--clear", "--subject", "leads.>"],
            ["--clear", "--stream", "LEADS"],
        ] {
            assert!(set(&both).is_err(), "{both:?}");
        }
    }

    fn policy_action(args: &[&str]) -> Result<PolicyAction, clap::Error> {
        let argv = ["cufflink", "tenants", "policy"].iter().chain(args);
        match Cli::try_parse_from(argv)?.command {
            Commands::Tenants {
                action: TenantsAction::Policy { action },
                ..
            } => Ok(action),
            _ => panic!("not a policy command"),
        }
    }

    fn generate_client_args(args: &[&str]) -> commands::openapi::GenerateClientArgs {
        let argv = ["cufflink", "generate-client"].iter().chain(args);
        match Cli::try_parse_from(argv).expect("parses").command {
            Commands::GenerateClient(args) => args,
            _ => panic!("not generate-client"),
        }
    }

    #[test]
    fn generate_client_flags_are_unchanged() {
        let defaults = generate_client_args(&[]);
        assert_eq!(defaults.output, "./generated");
        assert!(!defaults.local);
        assert_eq!(defaults.tenant_slug, None);
        let local = generate_client_args(&[
            "--local",
            "--output",
            "clients/typescript",
            "--tenant-slug",
            "acme",
        ]);
        assert_eq!(local.output, "clients/typescript");
        assert!(local.local);
        assert_eq!(local.tenant_slug.as_deref(), Some("acme"));
        assert_eq!(generate_client_args(&["-o", "out"]).output, "out");
        let with_env = Cli::try_parse_from(["cufflink", "generate-client", "--env", "staging"])
            .expect("parses");
        assert_eq!(with_env.env.as_deref(), Some("staging"));
    }

    #[test]
    fn policy_set_parses_key_mode_and_config() {
        match policy_action(&[
            "set",
            "mantis",
            "storage_scope",
            "enforce",
            "--config",
            r#"{"scope":"strict"}"#,
        ])
        .expect("parses")
        {
            PolicyAction::Set {
                slug,
                key,
                mode,
                config,
            } => {
                assert_eq!(slug, "mantis");
                assert_eq!(key, PolicyKey::StorageScope);
                assert_eq!(mode, PolicyMode::Enforce);
                assert_eq!(config, Some(serde_json::json!({"scope": "strict"})));
            }
            _ => panic!("expected set"),
        }
    }

    #[test]
    fn policy_set_rejects_unknown_keys_modes_and_bad_json() {
        assert!(policy_action(&["set", "t", "secret_rotation", "warn"]).is_err());
        assert!(policy_action(&["set", "t", "egress", "loud"]).is_err());
        assert!(policy_action(&["set", "t", "egress", "warn", "--config", "{"]).is_err());
        assert!(matches!(
            policy_action(&["reset", "t", "graphql"]).expect("parses"),
            PolicyAction::Reset {
                key: PolicyKey::Graphql,
                ..
            }
        ));
    }

    #[test]
    fn the_r3_policies_are_settable_keys() {
        for (name, key) in [
            ("outbox", PolicyKey::Outbox),
            ("db_roles", PolicyKey::DbRoles),
            ("schema_guard", PolicyKey::SchemaGuard),
        ] {
            assert!(
                matches!(
                    policy_action(&["set", "mantis", name, "enforce"]).expect("parses"),
                    PolicyAction::Set { key: parsed, mode: PolicyMode::Enforce, .. } if parsed == key
                ),
                "{name}"
            );
        }
    }

    #[test]
    fn a_refused_plan_exits_3_and_any_other_failure_1() {
        let refused: eyre::Report = commands::deploy::Refused { body: "{}".into() }.into();
        assert_eq!(exit_code(&refused), 3);
        assert_eq!(exit_code(&refused.wrap_err("while planning")), 3);
        assert_eq!(exit_code(&eyre::eyre!("Plan failed (409 Conflict)")), 1);
    }

    #[test]
    fn strict_filters_is_a_settable_key() {
        assert!(matches!(
            policy_action(&["set", "mantis", "strict_filters", "enforce"]).expect("parses"),
            PolicyAction::Set {
                key: PolicyKey::StrictFilters,
                mode: PolicyMode::Enforce,
                config: None,
                ..
            }
        ));
    }
}