servicenow-cli 0.5.2

Fast, safe, human-friendly ServiceNow operations from the terminal
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
use std::io::Read;
use std::process::{Command, Stdio};

use assert_cmd::prelude::*;
use predicates::prelude::*;
use tempfile::TempDir;
use wiremock::matchers::{body_bytes, header, method, path, query_param};
use wiremock::{Mock, MockServer, ResponseTemplate};

fn command(config_home: &TempDir) -> Command {
    let mut command = Command::cargo_bin("servicenow").unwrap();
    command
        .env("XDG_CONFIG_HOME", config_home.path())
        .env(
            "SERVICENOW_CONFIG_DIR",
            config_home.path().join("servicenow"),
        )
        .env("XDG_CACHE_HOME", config_home.path().join("cache"))
        .env(
            "SERVICENOW_CACHE_DIR",
            config_home.path().join("cache/servicenow"),
        )
        .env_remove("SERVICENOW_INSTANCE")
        .env_remove("SERVICENOW_USERNAME")
        .env_remove("SERVICENOW_PASSWORD")
        .env_remove("SERVICENOW_COOKIE")
        .env_remove("SERVICENOW_USER_TOKEN")
        .env_remove("SERVICENOW_TOKEN")
        .env_remove("SERVICENOW_AUTH_TYPE")
        .env_remove("SERVICENOW_PROFILE")
        .env_remove("SERVICENOW_READ_ONLY")
        .env_remove("SERVICENOW_VERBOSE");
    command
}

/// Runs `args`, closing our end of its stdout pipe before it can write anything, then
/// returns its stderr and exit status. Reproduces "the reader went away" the same way
/// `head -c N` does: because the read end is fully closed before the child's first write,
/// even a small amount of output is enough to trigger a broken pipe.
fn run_with_stdout_closed_early(
    config_home: &TempDir,
    args: &[&str],
) -> (String, std::process::ExitStatus) {
    let mut child = command(config_home)
        .args(args)
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();
    drop(child.stdout.take().unwrap());
    let mut stderr = String::new();
    child
        .stderr
        .take()
        .unwrap()
        .read_to_string(&mut stderr)
        .unwrap();
    let status = child.wait().unwrap();
    (stderr, status)
}

#[test]
fn schema_output_survives_a_closed_stdout_pipe() {
    let config_home = TempDir::new().unwrap();
    let (stderr, status) = run_with_stdout_closed_early(&config_home, &["schema"]);
    assert!(stderr.is_empty(), "stderr: {stderr}");
    assert_eq!(status.code(), Some(0));
}

#[test]
fn completions_output_survives_a_closed_stdout_pipe() {
    let config_home = TempDir::new().unwrap();
    let (stderr, status) = run_with_stdout_closed_early(&config_home, &["completions", "zsh"]);
    assert!(stderr.is_empty(), "stderr: {stderr}");
    assert_eq!(status.code(), Some(0));
}

#[test]
fn unknown_flag_under_json_output_uses_the_error_envelope() {
    let config_home = TempDir::new().unwrap();
    let output = command(&config_home)
        .args(["--output", "json", "incidents", "list", "--bogus-flag"])
        .output()
        .unwrap();
    assert_eq!(output.status.code(), Some(2));
    assert!(output.stdout.is_empty());
    let error: serde_json::Value = serde_json::from_slice(&output.stderr).unwrap();
    assert_eq!(error["error"]["kind"], "invalid_input");
    assert!(
        error["error"]["message"]
            .as_str()
            .unwrap()
            .contains("--bogus-flag")
    );
}

#[test]
fn missing_required_argument_under_json_output_uses_the_error_envelope() {
    let config_home = TempDir::new().unwrap();
    let output = command(&config_home)
        .args(["--output", "json", "tables", "get"])
        .output()
        .unwrap();
    assert_eq!(output.status.code(), Some(2));
    let error: serde_json::Value = serde_json::from_slice(&output.stderr).unwrap();
    assert_eq!(error["error"]["kind"], "invalid_input");
}

#[test]
fn unknown_subcommand_under_json_output_uses_the_error_envelope() {
    let config_home = TempDir::new().unwrap();
    let output = command(&config_home)
        .args(["--output", "json", "bogus-subcommand"])
        .output()
        .unwrap();
    assert_eq!(output.status.code(), Some(2));
    let error: serde_json::Value = serde_json::from_slice(&output.stderr).unwrap();
    assert_eq!(error["error"]["kind"], "invalid_input");
}

#[test]
fn unknown_flag_under_text_output_keeps_the_plain_usage_error() {
    let config_home = TempDir::new().unwrap();
    for format in [&["--output", "text"][..], &["-otext"]] {
        let output = command(&config_home)
            .args(format)
            .args(["incidents", "list", "--bogus-flag"])
            .output()
            .unwrap();
        assert_eq!(output.status.code(), Some(2), "{format:?}");
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(stderr.starts_with("error: "), "{format:?}: {stderr}");
    }
}

#[test]
fn help_and_version_are_unaffected_by_json_output() {
    let config_home = TempDir::new().unwrap();
    command(&config_home)
        .args(["--output", "json", "--help"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Fast, safe, human-friendly"));
    command(&config_home)
        .args(["--output", "json", "--version"])
        .assert()
        .success()
        .stdout(predicate::str::contains("servicenow"));
}

#[test]
fn empty_csv_result_prints_nothing() {
    let config_home = TempDir::new().unwrap();
    let output = command(&config_home)
        .args(["--output", "csv", "profile", "list"])
        .output()
        .unwrap();
    assert!(output.status.success());
    assert!(
        output.stdout.is_empty(),
        "stdout: {:?}",
        String::from_utf8_lossy(&output.stdout)
    );
}

#[test]
fn tables_delete_refusal_message_matches_other_delete_commands() {
    let config_home = TempDir::new().unwrap();
    let output = command(&config_home)
        .env("SERVICENOW_INSTANCE", "http://127.0.0.1:9")
        .env("SERVICENOW_USERNAME", "api-user")
        .env("SERVICENOW_PASSWORD", "secret")
        .args([
            "tables",
            "delete",
            "incident",
            "0123456789abcdef0123456789abcdef",
        ])
        .output()
        .unwrap();
    assert_eq!(output.status.code(), Some(2));
    let error: serde_json::Value = serde_json::from_slice(&output.stderr).unwrap();
    let message = error["error"]["message"].as_str().unwrap();
    // Old behavior unconditionally refused with "rerun with --yes"; the fixed behavior
    // matches the cancellation wording `profile remove` and `attachments delete` already
    // use for a non-interactive refusal.
    assert!(message.contains("cancelled"), "message: {message}");
    assert!(message.contains("non-interactive"), "message: {message}");
}

#[test]
fn auth_login_help_advertises_secret_free_verbose_progress() {
    let config_home = TempDir::new().unwrap();
    command(&config_home)
        .args(["auth", "login", "--help"])
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "Show secret-free browser sign-in progress on stderr",
        ));
}

#[test]
fn tui_help_describes_incident_operations_and_generic_browsing() {
    let config_home = TempDir::new().unwrap();
    command(&config_home)
        .args(["tui", "--help"])
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "Operate incidents and browse ServiceNow tables interactively",
        ))
        .stdout(predicate::str::contains("Table to open first"))
        .stdout(predicate::str::contains("--page-size"));
}

#[test]
fn tui_refuses_non_interactive_streams_before_loading_credentials() {
    let config_home = TempDir::new().unwrap();
    command(&config_home)
        .arg("tui")
        .assert()
        .code(2)
        .stderr(predicate::str::contains(
            "the TUI requires an interactive terminal on stdin and stdout",
        ));
}

#[test]
fn tui_rejects_an_unbounded_page_size() {
    let config_home = TempDir::new().unwrap();
    command(&config_home)
        .args(["tui", "--page-size", "4"])
        .assert()
        .code(2)
        .stderr(predicate::str::contains(
            "page size must be between 5 and 200",
        ));
}

fn authenticated_command(config_home: &TempDir, server: &MockServer) -> Command {
    let mut command = command(config_home);
    command
        .env("SERVICENOW_INSTANCE", server.uri())
        .env("SERVICENOW_USERNAME", "admin")
        .env("SERVICENOW_PASSWORD", "secret");
    command
}

fn cache_incident_resolution_choices(config_home: &TempDir) {
    let path = config_home
        .path()
        .join("cache/servicenow/metadata/default/incident.json");
    std::fs::create_dir_all(path.parent().unwrap()).unwrap();
    std::fs::write(
        path,
        serde_json::to_vec_pretty(&serde_json::json!({
            "table": "incident",
            "fetched_at": 1,
            "fields": [],
            "choices": {
                "state": [
                    {"value": "2", "label": "In Progress", "sequence": 20},
                    {"value": "9", "label": "Resolved", "sequence": 90},
                    {"value": "7", "label": "Closed", "sequence": 100}
                ],
                "close_code": [
                    {
                        "value": "solved_permanently",
                        "label": "Solved (Permanently)",
                        "sequence": 10
                    },
                    {
                        "value": "solved_workaround",
                        "label": "Solved (Work Around)",
                        "sequence": 20
                    }
                ]
            }
        }))
        .unwrap(),
    )
    .unwrap();
}

#[test]
fn schema_is_offline_and_machine_readable() {
    let config_home = TempDir::new().unwrap();
    let output = command(&config_home).arg("schema").output().unwrap();
    assert!(output.status.success());
    let schema: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(schema["name"], "servicenow");
    assert_eq!(schema["schemaVersion"], "1.0");
    assert_eq!(schema["outputContract"]["listEnvelope"]["count"], "integer");
    assert!(schema["commands"].as_array().unwrap().len() >= 5);
}

#[test]
fn schema_can_describe_one_command_compactly() {
    let config_home = TempDir::new().unwrap();
    let output = command(&config_home)
        .args(["schema", "--command", "incidents list"])
        .output()
        .unwrap();
    assert!(output.status.success());
    let schema: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(schema["name"], "list");
    assert_eq!(schema["path"], "incidents list");
    assert_eq!(schema["schemaVersion"], "1.0");
    let arguments = schema["arguments"].as_array().unwrap();
    let display_value = arguments
        .iter()
        .find(|argument| argument["id"] == "display_value")
        .unwrap();
    assert_eq!(display_value["type"], "enum");
    assert_eq!(display_value["possibleValues"][2], "all");
    assert!(
        display_value["dynamicDefault"]
            .as_str()
            .unwrap()
            .contains("machine")
    );
}

#[test]
fn init_schema_describes_adaptive_onboarding_defaults() {
    let config_home = TempDir::new().unwrap();
    let output = command(&config_home)
        .args(["schema", "--command", "init"])
        .output()
        .unwrap();
    assert!(output.status.success());
    let schema: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    let method = schema["arguments"]
        .as_array()
        .unwrap()
        .iter()
        .find(|argument| argument["id"] == "method")
        .unwrap();
    assert!(
        method["possibleValues"]
            .as_array()
            .unwrap()
            .contains(&"browser".into())
    );
    assert!(
        method["possibleValues"]
            .as_array()
            .unwrap()
            .contains(&"oauth".into())
    );
    assert!(
        !method["possibleValues"]
            .as_array()
            .unwrap()
            .contains(&"o-auth".into())
    );
    let arguments = schema["arguments"].as_array().unwrap();
    let dynamic_default = |id: &str| {
        arguments
            .iter()
            .find(|argument| argument["id"] == id)
            .unwrap()["dynamicDefault"]
            .as_str()
            .unwrap()
    };
    assert!(dynamic_default("method").contains("detected"));
    assert!(dynamic_default("scope").contains("useraccount"));
    assert!(dynamic_default("redirect_uri").contains("8484"));
}

#[test]
fn schema_marks_destructive_and_dry_run_commands() {
    let config_home = TempDir::new().unwrap();
    let deletion = command(&config_home)
        .args(["schema", "--command", "attachments delete"])
        .output()
        .unwrap();
    let deletion: serde_json::Value = serde_json::from_slice(&deletion.stdout).unwrap();
    assert_eq!(deletion["behavior"]["destructive"], true);
    assert_eq!(deletion["behavior"]["requiresConfirmation"], true);
    assert_eq!(deletion["behavior"]["supportsDryRun"], true);

    let resolution = command(&config_home)
        .args(["schema", "--command", "incidents resolve"])
        .output()
        .unwrap();
    let resolution: serde_json::Value = serde_json::from_slice(&resolution.stdout).unwrap();
    assert_eq!(resolution["behavior"]["mutation"], true);
    assert_eq!(resolution["behavior"]["destructive"], false);
    assert_eq!(resolution["behavior"]["requiresConfirmation"], false);
    assert_eq!(resolution["behavior"]["supportsDryRun"], true);
    assert_eq!(resolution["argumentGroups"][0]["required"], true);
    assert_eq!(
        resolution["argumentGroups"][0]["arguments"],
        serde_json::json!(["notes", "notes_file"])
    );
    let state = resolution["arguments"]
        .as_array()
        .unwrap()
        .iter()
        .find(|argument| argument["id"] == "state")
        .unwrap();
    assert!(
        state["dynamicDefault"]
            .as_str()
            .unwrap()
            .contains("Resolved")
    );

    let tui = command(&config_home)
        .args(["schema", "--command", "tui"])
        .output()
        .unwrap();
    let tui: serde_json::Value = serde_json::from_slice(&tui.stdout).unwrap();
    assert_eq!(tui["behavior"]["mutation"], true);
    assert_eq!(tui["behavior"]["sideEffect"], "remote");
    assert_eq!(tui["behavior"]["requiresConfirmation"], true);
    assert_eq!(tui["behavior"]["supportsDryRun"], false);
}

#[tokio::test]
async fn incident_machine_output_keeps_raw_values_by_default() {
    let config_home = TempDir::new().unwrap();
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/now/table/incident"))
        .and(query_param("sysparm_display_value", "false"))
        .and(query_param(
            "sysparm_fields",
            "sys_id,number,short_description,state,priority,assigned_to,sys_updated_on",
        ))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "result": [{"sys_id": "0123456789abcdef0123456789abcdef", "number": "INC0010001", "state": "2"}]
        })))
        .expect(1)
        .mount(&server)
        .await;

    let output = authenticated_command(&config_home, &server)
        .args(["incidents", "list", "--limit", "1"])
        .output()
        .unwrap();
    assert!(output.status.success());
    let value: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(value["count"], 1);
    assert_eq!(value["result"][0]["state"], "2");
    assert_eq!(
        value["result"][0]["sys_id"],
        "0123456789abcdef0123456789abcdef"
    );
}

#[tokio::test]
async fn successful_commands_persist_rotated_browser_cookies() {
    let config_home = TempDir::new().unwrap();
    let server = MockServer::start().await;
    let config_dir = config_home.path().join("servicenow");
    std::fs::create_dir_all(&config_dir).unwrap();
    std::fs::write(
        config_dir.join("config.toml"),
        format!(
            r#"active_profile = "work"

[profiles.work]
instance = "{}"
auth_type = "browser"
credential_store = "file"

[profiles.work.credential]
kind = "browser"
cookie = "JSESSIONID=initial-session"
user_token = "synthetic-user-token"
"#,
            server.uri()
        ),
    )
    .unwrap();
    Mock::given(method("GET"))
        .and(path("/api/now/table/incident"))
        .and(header("cookie", "JSESSIONID=initial-session"))
        .respond_with(
            ResponseTemplate::new(200)
                .insert_header("set-cookie", "JSESSIONID=rotated-session; Path=/; HttpOnly")
                .set_body_json(serde_json::json!({"result": []})),
        )
        .expect(1)
        .mount(&server)
        .await;

    command(&config_home)
        .args(["--profile", "work", "incidents", "list", "--limit", "1"])
        .assert()
        .success();

    let config = std::fs::read_to_string(config_dir.join("config.toml")).unwrap();
    assert!(config.contains("cookie = \"JSESSIONID=rotated-session\""));
    assert!(!config.contains("JSESSIONID=initial-session"));
}

#[tokio::test]
async fn rejected_commands_do_not_persist_response_cookies() {
    let config_home = TempDir::new().unwrap();
    let server = MockServer::start().await;
    let config_dir = config_home.path().join("servicenow");
    std::fs::create_dir_all(&config_dir).unwrap();
    std::fs::write(
        config_dir.join("config.toml"),
        format!(
            r#"active_profile = "work"

[profiles.work]
instance = "{}"
auth_type = "browser"
credential_store = "file"

[profiles.work.credential]
kind = "browser"
cookie = "JSESSIONID=last-known-good"
user_token = "synthetic-user-token"
"#,
            server.uri()
        ),
    )
    .unwrap();
    Mock::given(method("GET"))
        .and(path("/api/now/table/incident"))
        .respond_with(
            ResponseTemplate::new(401)
                .insert_header(
                    "set-cookie",
                    "JSESSIONID=rejected-session; Path=/; HttpOnly",
                )
                .set_body_json(serde_json::json!({
                    "error": {"message": "User is not authenticated", "detail": "Session expired"}
                })),
        )
        .expect(1)
        .mount(&server)
        .await;

    command(&config_home)
        .args(["--profile", "work", "incidents", "list", "--limit", "1"])
        .assert()
        .code(3);

    let config = std::fs::read_to_string(config_dir.join("config.toml")).unwrap();
    assert!(config.contains("cookie = \"JSESSIONID=last-known-good\""));
    assert!(!config.contains("JSESSIONID=rejected-session"));
}

#[tokio::test]
async fn incident_text_output_prefers_display_values_and_curated_columns() {
    let config_home = TempDir::new().unwrap();
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/now/table/incident"))
        .and(query_param("sysparm_display_value", "true"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "result": [{
                "sys_id": "0123456789abcdef0123456789abcdef",
                "number": "INC0010001",
                "priority": "1 - Critical",
                "short_description": "Email is unavailable",
                "state": "In Progress",
                "assigned_to": "Don Goodliffe",
                "sys_updated_on": "2026-08-22 10:30:00"
            }]
        })))
        .expect(1)
        .mount(&server)
        .await;

    let output = authenticated_command(&config_home, &server)
        .args(["--output", "table", "incidents", "list", "--limit", "1"])
        .output()
        .unwrap();
    assert!(output.status.success());
    let text = String::from_utf8(output.stdout).unwrap();
    assert!(text.contains("DESCRIPTION"));
    assert!(text.contains("ASSIGNEE"));
    assert!(text.contains("Don Goodliffe"));
    assert!(!text.contains("SYS ID"));
    assert!(!text.contains("0123456789abcdef0123456789abcdef"));
}

#[test]
fn config_init_does_not_require_credentials() {
    let config_home = TempDir::new().unwrap();
    command(&config_home)
        .args(["config", "init"])
        .assert()
        .success()
        .stdout(predicate::str::contains("configPath"));
}

#[tokio::test]
async fn init_can_fall_back_to_the_protected_config_file() {
    let config_home = TempDir::new().unwrap();
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/now/table/sys_user"))
        .and(query_param(
            "sysparm_query",
            "sys_id=javascript:gs.getUserID()",
        ))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "result": [{
                "sys_id": "0123456789abcdef0123456789abcdef",
                "user_name": "admin",
                "name": "Admin User"
            }]
        })))
        .expect(1)
        .mount(&server)
        .await;

    let mut init = assert_cmd::Command::from_std(command(&config_home));
    let output = init
        .args([
            "init",
            "--profile",
            "work",
            "--instance",
            &server.uri(),
            "--username",
            "admin",
            "--method",
            "basic",
            "--secret-stdin",
            "--insecure-storage",
        ])
        .write_stdin("secret\n")
        .output()
        .unwrap();
    assert!(output.status.success());
    let result: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(result["credentialStore"], "config-file");
    assert!(
        String::from_utf8(output.stderr)
            .unwrap()
            .contains("stored in plaintext")
    );

    let config_path = config_home.path().join("servicenow/config.toml");
    let config = std::fs::read_to_string(&config_path).unwrap();
    assert!(config.contains("credential_store = \"file\""));
    assert!(config.contains("password = \"secret\""));
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        assert_eq!(
            std::fs::metadata(&config_path)
                .unwrap()
                .permissions()
                .mode()
                & 0o777,
            0o600
        );
    }

    let shown = command(&config_home)
        .args(["--profile", "work", "config", "show"])
        .output()
        .unwrap();
    assert!(shown.status.success());
    let shown: serde_json::Value = serde_json::from_slice(&shown.stdout).unwrap();
    assert_eq!(shown["secretMasked"], "***cret");

    command(&config_home)
        .args(["auth", "logout", "--profile", "work"])
        .assert()
        .success();
    let config = std::fs::read_to_string(config_path).unwrap();
    assert!(!config.contains("password = \"secret\""));
}

#[tokio::test]
async fn init_detects_microsoft_entra_and_selects_zero_admin_browser_sign_in() {
    let config_home = TempDir::new().unwrap();
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/nav_to.do"))
        .respond_with(ResponseTemplate::new(302).insert_header(
            "location",
            "/auth_redirect.do?sysparm_url=https%3A%2F%2Flogin.microsoftonline.com%2Fexample%2Fsaml2",
        ))
        .expect(1)
        .mount(&server)
        .await;

    command(&config_home)
        .args([
            "init",
            "work",
            "--instance",
            &server.uri(),
            "--insecure-storage",
            "--no-browser",
        ])
        .assert()
        .failure()
        .stderr(predicate::str::contains("Microsoft Entra SSO detected"))
        .stderr(predicate::str::contains(
            "no ServiceNow password or OAuth application is required",
        ))
        .stderr(predicate::str::contains("remove --no-browser"));
}

#[tokio::test]
async fn init_does_not_treat_a_local_login_form_as_basic_authentication() {
    let config_home = TempDir::new().unwrap();
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/nav_to.do"))
        .and(query_param("uri", "incident_list.do"))
        .respond_with(ResponseTemplate::new(302).insert_header("location", "/login.do"))
        .expect(1)
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/login.do"))
        .respond_with(ResponseTemplate::new(200).set_body_string("<form>Password</form>"))
        .expect(1)
        .mount(&server)
        .await;

    command(&config_home)
        .args(["init", "work", "--instance", &server.uri()])
        .assert()
        .failure()
        .stderr(predicate::str::contains(
            "did not expose a definitive login method",
        ))
        .stderr(predicate::str::contains("username/password login detected").not());
}

#[tokio::test]
async fn rejected_basic_auth_on_federated_instance_recommends_browser_sign_in() {
    let config_home = TempDir::new().unwrap();
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/now/table/sys_user"))
        .respond_with(ResponseTemplate::new(401).set_body_json(serde_json::json!({
            "error": {
                "message": "User is not authenticated",
                "detail": "Required to provide Auth information"
            }
        })))
        .expect(1)
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/nav_to.do"))
        .respond_with(ResponseTemplate::new(302).insert_header(
            "location",
            "/auth_redirect.do?sysparm_url=https%3A%2F%2Flogin.microsoftonline.com%2Ftenant-guid%2Fsaml2",
        ))
        .expect(1)
        .mount(&server)
        .await;

    let mut init = assert_cmd::Command::from_std(command(&config_home));
    init.args([
        "init",
        "work",
        "--instance",
        &server.uri(),
        "--username",
        "federated-user",
        "--method",
        "basic",
        "--secret-stdin",
        "--insecure-storage",
    ])
    .write_stdin("not-a-servicenow-password\n")
    .assert()
    .failure()
    .stderr(predicate::str::contains("Microsoft Entra SSO"))
    .stderr(predicate::str::contains("Federated accounts"))
    .stderr(predicate::str::contains("--method browser"))
    .stderr(predicate::str::contains("no OAuth application"))
    .stderr(predicate::str::contains("Application Registry").not())
    .stderr(predicate::str::contains("servicenow auth login").not());
}

#[tokio::test]
async fn auth_login_resumes_a_saved_profile_without_reasking_for_the_instance() {
    let config_home = TempDir::new().unwrap();
    let server = MockServer::start().await;
    let config_dir = config_home.path().join("servicenow");
    std::fs::create_dir_all(&config_dir).unwrap();
    std::fs::write(
        config_dir.join("config.toml"),
        format!(
            "active_profile = \"work\"\n\n[profiles.work]\ninstance = \"{}\"\nauth_type = \"basic\"\n",
            server.uri()
        ),
    )
    .unwrap();
    Mock::given(method("GET"))
        .and(path("/api/now/table/sys_user"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "result": [{
                "sys_id": "0123456789abcdef0123456789abcdef",
                "user_name": "admin",
                "name": "Admin User"
            }]
        })))
        .expect(1)
        .mount(&server)
        .await;

    let mut login = assert_cmd::Command::from_std(command(&config_home));
    login
        .args([
            "auth",
            "login",
            "--profile",
            "work",
            "--username",
            "admin",
            "--method",
            "basic",
            "--secret-stdin",
            "--insecure-storage",
        ])
        .write_stdin("secret\n")
        .assert()
        .success()
        .stderr(predicate::str::contains("Resuming profile 'work'"));
}

#[test]
fn profile_selection_rejects_ambiguous_global_and_legacy_inputs() {
    let config_home = TempDir::new().unwrap();
    command(&config_home)
        .args(["init", "legacy", "--profile", "preferred"])
        .assert()
        .code(2)
        .stderr(predicate::str::contains(
            "--profile or the legacy positional argument, not both",
        ));
}

#[test]
fn offline_auth_status_and_doctor_do_not_require_instance_access() {
    let config_home = TempDir::new().unwrap();
    let mut offline = command(&config_home);
    offline
        .env("SERVICENOW_INSTANCE", "offline.invalid")
        .env("SERVICENOW_USERNAME", "api-user")
        .env("SERVICENOW_PASSWORD", "secret");

    let status = offline
        .args(["auth", "status", "--offline"])
        .output()
        .unwrap();
    assert!(status.status.success());
    let status: serde_json::Value = serde_json::from_slice(&status.stdout).unwrap();
    assert_eq!(status["status"], "configured");
    assert_eq!(status["verified"], false);
    assert_eq!(status["credentialStore"], "environment");

    let doctor = command(&config_home)
        .env("SERVICENOW_INSTANCE", "offline.invalid")
        .env("SERVICENOW_USERNAME", "api-user")
        .env("SERVICENOW_PASSWORD", "secret")
        .args(["doctor", "--offline"])
        .output()
        .unwrap();
    assert!(doctor.status.success());
    let doctor: serde_json::Value = serde_json::from_slice(&doctor.stdout).unwrap();
    assert_eq!(doctor["offline"], true);
    assert_eq!(doctor["verified"], false);
    assert_eq!(doctor["checks"][3]["name"], "table_api");
    assert_eq!(doctor["checks"][3]["skipped"], true);
    assert!(doctor["checks"][3].get("ok").is_none());
    assert_eq!(doctor["checks"][3]["detail"], "network check skipped");
}

#[tokio::test]
async fn auth_status_verifies_the_current_identity_without_reading_incidents() {
    let config_home = TempDir::new().unwrap();
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/now/table/sys_user"))
        .and(query_param(
            "sysparm_query",
            "sys_id=javascript:gs.getUserID()",
        ))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "result": [{
                "sys_id": "0123456789abcdef0123456789abcdef",
                "user_name": "admin",
                "name": "System Administrator"
            }]
        })))
        .expect(1)
        .mount(&server)
        .await;

    let output = authenticated_command(&config_home, &server)
        .args(["auth", "status"])
        .output()
        .unwrap();
    assert!(output.status.success());
    let result: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(result["status"], "ok");
    assert_eq!(result["verified"], true);
    assert_eq!(result["identity"], "admin");
}

#[tokio::test]
async fn auth_status_uses_the_display_name_when_username_is_missing() {
    let config_home = TempDir::new().unwrap();
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/now/table/sys_user"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "result": [{
                "sys_id": "0123456789abcdef0123456789abcdef",
                "name": "System Administrator"
            }]
        })))
        .expect(1)
        .mount(&server)
        .await;

    let output = authenticated_command(&config_home, &server)
        .args(["auth", "status"])
        .output()
        .unwrap();
    assert!(output.status.success());
    let result: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(result["identity"], "System Administrator");
}

#[test]
fn auth_status_and_doctor_schema_mark_network_access_as_conditional() {
    let config_home = TempDir::new().unwrap();
    for path in ["auth status", "doctor"] {
        let output = command(&config_home)
            .args(["schema", "--command", path])
            .output()
            .unwrap();
        assert!(output.status.success());
        let schema: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
        assert_eq!(schema["behavior"]["networkAccess"], "conditional");
    }
}

#[test]
fn missing_config_has_structured_error_and_input_exit_code() {
    let config_home = TempDir::new().unwrap();
    let output = command(&config_home)
        .args(["config", "show"])
        .output()
        .unwrap();
    assert_eq!(output.status.code(), Some(2));
    assert!(output.stdout.is_empty());
    let error: serde_json::Value = serde_json::from_slice(&output.stderr).unwrap();
    assert_eq!(error["error"]["kind"], "invalid_input");
}

#[test]
fn config_show_masks_password() {
    let config_home = TempDir::new().unwrap();
    let config_dir = config_home.path().join("servicenow");
    std::fs::create_dir_all(&config_dir).unwrap();
    std::fs::write(
        config_dir.join("config.toml"),
        r#"[default]
instance = "dev12345"
username = "api-user"
password = "very-secret"
"#,
    )
    .unwrap();

    let output = command(&config_home)
        .args(["config", "show"])
        .output()
        .unwrap();
    assert!(output.status.success());
    let value: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(value["secretMasked"], "***cret");
    assert!(
        !String::from_utf8(output.stdout)
            .unwrap()
            .contains("very-secret")
    );
}

#[test]
fn delete_requires_explicit_confirmation_before_network_access() {
    let config_home = TempDir::new().unwrap();
    let output = command(&config_home)
        .env("SERVICENOW_INSTANCE", "http://127.0.0.1:9")
        .env("SERVICENOW_USERNAME", "api-user")
        .env("SERVICENOW_PASSWORD", "secret")
        .args([
            "tables",
            "delete",
            "incident",
            "0123456789abcdef0123456789abcdef",
        ])
        .output()
        .unwrap();
    assert_eq!(output.status.code(), Some(2));
    let error: serde_json::Value = serde_json::from_slice(&output.stderr).unwrap();
    assert!(
        error["error"]["message"]
            .as_str()
            .unwrap()
            .contains("--yes")
    );
}

#[tokio::test]
async fn doctor_verifies_authentication_and_table_access() {
    let config_home = TempDir::new().unwrap();
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/now/table/sys_user"))
        .and(query_param(
            "sysparm_query",
            "sys_id=javascript:gs.getUserID()",
        ))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "result": [{
                "sys_id": "0123456789abcdef0123456789abcdef",
                "user_name": "admin",
                "name": "System Administrator",
                "active": "true"
            }]
        })))
        .expect(1)
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/api/now/table/incident"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "result": []
        })))
        .expect(1)
        .mount(&server)
        .await;

    let output = command(&config_home)
        .env("SERVICENOW_INSTANCE", server.uri())
        .env("SERVICENOW_USERNAME", "admin")
        .env("SERVICENOW_PASSWORD", "secret")
        .arg("doctor")
        .output()
        .unwrap();

    assert!(output.status.success());
    let result: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(result["ok"], true);
    assert_eq!(result["checks"][1]["name"], "authentication");
    assert_eq!(result["checks"][1]["detail"], "admin");
    assert_eq!(result["checks"][2]["name"], "credentials");
    assert_eq!(result["checks"][2]["detail"], "environment variable");
    assert_eq!(result["checks"][3]["name"], "table_api");
}

#[tokio::test]
async fn table_lists_support_json_lines_yaml_and_csv() {
    let config_home = TempDir::new().unwrap();
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/now/table/incident"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "result": [{"number": "INC0010001", "state": "2"}]
        })))
        .expect(3)
        .mount(&server)
        .await;

    let jsonl = authenticated_command(&config_home, &server)
        .args([
            "--output", "jsonl", "tables", "list", "incident", "--limit", "1",
        ])
        .output()
        .unwrap();
    assert!(jsonl.status.success());
    let row: serde_json::Value = serde_json::from_slice(&jsonl.stdout).unwrap();
    assert_eq!(row["number"], "INC0010001");

    let yaml = authenticated_command(&config_home, &server)
        .args([
            "--output", "yaml", "tables", "list", "incident", "--limit", "1",
        ])
        .output()
        .unwrap();
    assert!(yaml.status.success());
    let yaml = String::from_utf8(yaml.stdout).unwrap();
    assert!(yaml.contains("number: INC0010001"));

    let csv = authenticated_command(&config_home, &server)
        .args([
            "--output", "csv", "tables", "list", "incident", "--limit", "1",
        ])
        .output()
        .unwrap();
    assert!(csv.status.success());
    let csv = String::from_utf8(csv.stdout).unwrap();
    assert!(csv.contains("number,state"));
    assert!(csv.contains("INC0010001,2"));
}

#[tokio::test]
async fn schema_refresh_caches_dictionary_and_choices() {
    let config_home = TempDir::new().unwrap();
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/now/table/sys_dictionary"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "result": [{
                "element": "state",
                "column_label": "State",
                "internal_type": "integer",
                "reference": "",
                "mandatory": "true",
                "read_only": "false"
            }]
        })))
        .expect(1)
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/api/now/table/sys_choice"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "result": [{
                "element": "state", "value": "2", "label": "In Progress", "sequence": "20"
            }]
        })))
        .expect(1)
        .mount(&server)
        .await;

    let output = authenticated_command(&config_home, &server)
        .args(["schema", "incident", "--refresh"])
        .output()
        .unwrap();
    assert!(output.status.success());
    let result: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(result["result"]["fields"][0]["name"], "state");
    assert_eq!(
        result["result"]["choices"]["state"][0]["label"],
        "In Progress"
    );
    assert!(
        config_home
            .path()
            .join("cache/servicenow/metadata/default/incident.json")
            .exists()
    );
}

#[tokio::test]
async fn incident_edit_applies_only_changed_fields() {
    let config_home = TempDir::new().unwrap();
    let server = MockServer::start().await;
    let sys_id = "0123456789abcdef0123456789abcdef";
    Mock::given(method("GET"))
        .and(path(format!("/api/now/table/incident/{sys_id}")))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "result": {
                "sys_id": sys_id,
                "short_description": "Before",
                "state": {"value": "2", "display_value": "In Progress"}
            }
        })))
        .expect(1)
        .mount(&server)
        .await;
    Mock::given(method("PATCH"))
        .and(path(format!("/api/now/table/incident/{sys_id}")))
        .and(wiremock::matchers::body_json(serde_json::json!({
            "short_description": "After"
        })))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "result": {"sys_id": sys_id, "number": "INC0010001", "short_description": "After"}
        })))
        .expect(1)
        .mount(&server)
        .await;
    let edit = tempfile::NamedTempFile::new().unwrap();
    std::fs::write(edit.path(), "short_description: After\nstate: '2'\n").unwrap();

    let output = authenticated_command(&config_home, &server)
        .args([
            "incidents",
            "edit",
            sys_id,
            "--file",
            edit.path().to_str().unwrap(),
            "--yes",
        ])
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    let result: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(result["result"]["short_description"], "After");
}

#[tokio::test]
async fn incident_resolve_dry_run_maps_configured_labels_without_patching() {
    let config_home = TempDir::new().unwrap();
    cache_incident_resolution_choices(&config_home);
    let server = MockServer::start().await;
    let sys_id = "0123456789abcdef0123456789abcdef";
    Mock::given(method("GET"))
        .and(path(format!("/api/now/table/incident/{sys_id}")))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "result": {
                "sys_id": sys_id,
                "number": "INC0010001",
                "state": {"value": "2", "display_value": "In Progress"}
            }
        })))
        .expect(1)
        .mount(&server)
        .await;
    Mock::given(method("PATCH"))
        .respond_with(ResponseTemplate::new(500))
        .expect(0)
        .mount(&server)
        .await;

    let output = authenticated_command(&config_home, &server)
        .env("SERVICENOW_READ_ONLY", "true")
        .args([
            "incidents",
            "resolve",
            sys_id,
            "--code",
            "solved (permanently)",
            "--notes",
            "Restored the VPN gateway configuration.",
            "--dry-run",
        ])
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    let result: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(result["operation"], "resolve");
    assert_eq!(result["changes"]["state"], "9");
    assert_eq!(result["changes"]["close_code"], "solved_permanently");
    assert_eq!(
        result["changes"]["close_notes"],
        "Restored the VPN gateway configuration."
    );
}

#[tokio::test]
async fn incident_resolve_patches_resolution_atomically_with_custom_fields() {
    let config_home = TempDir::new().unwrap();
    cache_incident_resolution_choices(&config_home);
    let server = MockServer::start().await;
    let sys_id = "0123456789abcdef0123456789abcdef";
    Mock::given(method("GET"))
        .and(path(format!("/api/now/table/incident/{sys_id}")))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "result": {
                "sys_id": sys_id,
                "number": "INC0010001",
                "state": {"value": "2", "display_value": "In Progress"}
            }
        })))
        .expect(1)
        .mount(&server)
        .await;
    Mock::given(method("PATCH"))
        .and(path(format!("/api/now/table/incident/{sys_id}")))
        .and(wiremock::matchers::body_json(serde_json::json!({
            "state": "9",
            "close_code": "solved_workaround",
            "close_notes": "Temporary route restored service.\n",
            "u_resolution_source": "network_runbook"
        })))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "result": {
                "sys_id": sys_id,
                "number": "INC0010001",
                "state": "9",
                "close_code": "solved_workaround"
            }
        })))
        .expect(1)
        .mount(&server)
        .await;
    let notes = tempfile::NamedTempFile::new().unwrap();
    std::fs::write(notes.path(), "Temporary route restored service.\n").unwrap();

    let output = authenticated_command(&config_home, &server)
        .args([
            "incidents",
            "resolve",
            sys_id,
            "--code",
            "Solved (Work Around)",
            "--notes-file",
            notes.path().to_str().unwrap(),
            "--field",
            "u_resolution_source=network_runbook",
        ])
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    let result: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(result["result"]["state"], "9");
    assert_eq!(result["result"]["close_code"], "solved_workaround");
    assert!(String::from_utf8_lossy(&output.stderr).contains("Resolved"));
}

#[tokio::test]
async fn incident_resolve_refuses_closed_incidents() {
    let config_home = TempDir::new().unwrap();
    cache_incident_resolution_choices(&config_home);
    let server = MockServer::start().await;
    let sys_id = "0123456789abcdef0123456789abcdef";
    Mock::given(method("GET"))
        .and(path(format!("/api/now/table/incident/{sys_id}")))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "result": {
                "sys_id": sys_id,
                "number": "INC0010001",
                "state": {"value": "7", "display_value": "Closed"}
            }
        })))
        .expect(1)
        .mount(&server)
        .await;
    Mock::given(method("PATCH"))
        .respond_with(ResponseTemplate::new(500))
        .expect(0)
        .mount(&server)
        .await;

    authenticated_command(&config_home, &server)
        .args([
            "incidents",
            "resolve",
            sys_id,
            "--code",
            "solved_permanently",
            "--notes",
            "Already closed.",
        ])
        .assert()
        .code(7)
        .stderr(predicate::str::contains("already Closed"));
}

#[tokio::test]
async fn incident_resolve_requires_non_empty_notes_before_network_access() {
    let config_home = TempDir::new().unwrap();
    let server = MockServer::start().await;
    authenticated_command(&config_home, &server)
        .args([
            "incidents",
            "resolve",
            "INC0010001",
            "--code",
            "solved_permanently",
            "--notes",
            "   ",
        ])
        .assert()
        .code(2)
        .stderr(predicate::str::contains("resolution notes cannot be empty"));
}

#[tokio::test]
async fn incident_note_dry_run_never_patches() {
    let config_home = TempDir::new().unwrap();
    let server = MockServer::start().await;
    let sys_id = "0123456789abcdef0123456789abcdef";
    Mock::given(method("GET"))
        .and(path(format!("/api/now/table/incident/{sys_id}")))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "result": {"sys_id": sys_id}
        })))
        .expect(1)
        .mount(&server)
        .await;

    let output = authenticated_command(&config_home, &server)
        .env("SERVICENOW_READ_ONLY", "true")
        .args(["incidents", "note", sys_id, "Investigating", "--dry-run"])
        .output()
        .unwrap();
    assert!(output.status.success());
    let result: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(result["dryRun"], true);
    assert_eq!(result["changes"]["work_notes"], "Investigating");
}

#[tokio::test]
async fn incident_assign_resolves_human_user_before_patching() {
    let config_home = TempDir::new().unwrap();
    let server = MockServer::start().await;
    let incident_id = "0123456789abcdef0123456789abcdef";
    let user_id = "fedcba9876543210fedcba9876543210";
    Mock::given(method("GET"))
        .and(path("/api/now/table/sys_user"))
        .and(query_param(
            "sysparm_query",
            "user_name=ada@example.com^ORemail=ada@example.com^ORname=ada@example.com",
        ))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "result": [{"sys_id": user_id, "user_name": "ada", "email": "ada@example.com"}]
        })))
        .expect(1)
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path(format!("/api/now/table/incident/{incident_id}")))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "result": {"sys_id": incident_id}
        })))
        .expect(1)
        .mount(&server)
        .await;
    Mock::given(method("PATCH"))
        .and(path(format!("/api/now/table/incident/{incident_id}")))
        .and(wiremock::matchers::body_json(serde_json::json!({
            "assigned_to": user_id
        })))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "result": {"sys_id": incident_id, "number": "INC0010001", "assigned_to": user_id}
        })))
        .expect(1)
        .mount(&server)
        .await;

    let output = authenticated_command(&config_home, &server)
        .args([
            "incidents",
            "assign",
            incident_id,
            "--to",
            "ada@example.com",
        ])
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    let result: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
    assert_eq!(result["result"]["assigned_to"], user_id);
}

#[tokio::test]
async fn incident_watch_is_a_bounded_json_event_stream() {
    let config_home = TempDir::new().unwrap();
    let server = MockServer::start().await;
    let sys_id = "0123456789abcdef0123456789abcdef";
    Mock::given(method("GET"))
        .and(path(format!("/api/now/table/incident/{sys_id}")))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "result": {"sys_id": sys_id, "number": "INC0010001", "state": "2"}
        })))
        .expect(2)
        .mount(&server)
        .await;

    let output = authenticated_command(&config_home, &server)
        .args([
            "incidents",
            "watch",
            sys_id,
            "--interval",
            "1",
            "--count",
            "1",
        ])
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "{}",
        String::from_utf8_lossy(&output.stderr)
    );
    let events = String::from_utf8(output.stdout).unwrap();
    let snapshot: serde_json::Value = serde_json::from_str(events.trim()).unwrap();
    assert_eq!(snapshot["event"], "snapshot");
    assert_eq!(snapshot["record"]["number"], "INC0010001");
}

#[tokio::test]
async fn attachment_commands_cover_the_complete_file_lifecycle() {
    let config_home = TempDir::new().unwrap();
    let files = TempDir::new().unwrap();
    let server = MockServer::start().await;
    let record_id = "0123456789abcdef0123456789abcdef";
    let attachment_id = "fedcba9876543210fedcba9876543210";
    let metadata = serde_json::json!({
        "sys_id": attachment_id,
        "file_name": "diagnostic.txt",
        "content_type": "text/plain",
        "size_bytes": "11",
        "table_name": "incident",
        "table_sys_id": record_id,
        "download_link": format!("{}/api/now/attachment/{attachment_id}/file", server.uri()),
        "sys_created_by": "admin",
        "sys_created_on": "2026-08-22 20:00:00"
    });

    Mock::given(method("GET"))
        .and(path("/api/now/table/incident"))
        .and(query_param("sysparm_query", "number=INC0010001"))
        .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({
            "result": [{"sys_id": record_id, "number": "INC0010001"}]
        })))
        .expect(2)
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/api/now/attachment"))
        .and(query_param(
            "sysparm_query",
            format!("table_name=incident^table_sys_id={record_id}^ORDERBYDESCsys_created_on"),
        ))
        .respond_with(
            ResponseTemplate::new(200)
                .set_body_json(serde_json::json!({"result": [metadata.clone()]})),
        )
        .expect(1)
        .mount(&server)
        .await;
    Mock::given(method("POST"))
        .and(path("/api/now/attachment/file"))
        .and(query_param("table_name", "incident"))
        .and(query_param("table_sys_id", record_id))
        .and(query_param("file_name", "diagnostic.txt"))
        .and(header("content-type", "text/plain"))
        .and(body_bytes(b"hello world"))
        .respond_with(
            ResponseTemplate::new(201)
                .set_body_json(serde_json::json!({"result": metadata.clone()})),
        )
        .expect(1)
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path(format!("/api/now/attachment/{attachment_id}")))
        .respond_with(
            ResponseTemplate::new(200)
                .set_body_json(serde_json::json!({"result": metadata.clone()})),
        )
        .expect(2)
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path(format!("/api/now/attachment/{attachment_id}/file")))
        .respond_with(ResponseTemplate::new(200).set_body_bytes(b"hello world"))
        .expect(1)
        .mount(&server)
        .await;
    Mock::given(method("DELETE"))
        .and(path(format!("/api/now/attachment/{attachment_id}")))
        .respond_with(ResponseTemplate::new(204))
        .expect(1)
        .mount(&server)
        .await;

    let listed = authenticated_command(&config_home, &server)
        .args(["attachments", "list", "incident", "INC0010001"])
        .output()
        .unwrap();
    assert!(listed.status.success());
    let listed: serde_json::Value = serde_json::from_slice(&listed.stdout).unwrap();
    assert_eq!(listed["count"], 1);
    assert_eq!(listed["result"][0]["file_name"], "diagnostic.txt");

    let source = files.path().join("diagnostic.txt");
    std::fs::write(&source, b"hello world").unwrap();
    let uploaded = authenticated_command(&config_home, &server)
        .args([
            "attachments",
            "upload",
            "incident",
            "INC0010001",
            source.to_str().unwrap(),
        ])
        .output()
        .unwrap();
    assert!(
        uploaded.status.success(),
        "{}",
        String::from_utf8_lossy(&uploaded.stderr)
    );
    let uploaded: serde_json::Value = serde_json::from_slice(&uploaded.stdout).unwrap();
    assert_eq!(uploaded["result"]["sys_id"], attachment_id);

    let destination = files.path().join("downloaded.txt");
    let downloaded = authenticated_command(&config_home, &server)
        .args([
            "attachments",
            "download",
            attachment_id,
            destination.to_str().unwrap(),
        ])
        .output()
        .unwrap();
    assert!(
        downloaded.status.success(),
        "{}",
        String::from_utf8_lossy(&downloaded.stderr)
    );
    assert_eq!(std::fs::read(&destination).unwrap(), b"hello world");
    let downloaded: serde_json::Value = serde_json::from_slice(&downloaded.stdout).unwrap();
    assert_eq!(downloaded["sizeBytes"], 11);

    let deleted = authenticated_command(&config_home, &server)
        .args(["attachments", "delete", attachment_id, "--yes"])
        .output()
        .unwrap();
    assert!(
        deleted.status.success(),
        "{}",
        String::from_utf8_lossy(&deleted.stderr)
    );
    let deleted: serde_json::Value = serde_json::from_slice(&deleted.stdout).unwrap();
    assert_eq!(deleted["deleted"], true);
}

#[test]
fn attachment_delete_is_blocked_by_read_only_mode_before_network_access() {
    let config_home = TempDir::new().unwrap();
    let output = command(&config_home)
        .env("SERVICENOW_INSTANCE", "http://127.0.0.1:9")
        .env("SERVICENOW_USERNAME", "api-user")
        .env("SERVICENOW_PASSWORD", "secret")
        .env("SERVICENOW_READ_ONLY", "true")
        .args([
            "attachments",
            "delete",
            "0123456789abcdef0123456789abcdef",
            "--yes",
        ])
        .output()
        .unwrap();
    assert_eq!(output.status.code(), Some(2));
    let error: serde_json::Value = serde_json::from_slice(&output.stderr).unwrap();
    assert_eq!(error["error"]["kind"], "invalid_input");
    assert!(
        error["error"]["message"]
            .as_str()
            .unwrap()
            .contains("read-only")
    );
}

#[tokio::test]
async fn a_conflict_response_exits_with_the_conflict_code() {
    let config_home = TempDir::new().unwrap();
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/now/table/incident"))
        .respond_with(ResponseTemplate::new(409).set_body_json(serde_json::json!({
            "error": {"message": "Duplicate key", "detail": "Record already exists"}
        })))
        .mount(&server)
        .await;

    authenticated_command(&config_home, &server)
        .args(["incidents", "list", "--limit", "1"])
        .assert()
        .code(7)
        .stderr(predicate::str::contains("Record already exists"));
}

#[tokio::test]
async fn a_rate_limited_response_exits_with_the_rate_limit_code() {
    let config_home = TempDir::new().unwrap();
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/api/now/table/incident"))
        .respond_with(ResponseTemplate::new(429).set_body_json(serde_json::json!({
            "error": {"message": "Rate limit exceeded", "detail": "Too many requests"}
        })))
        .mount(&server)
        .await;

    authenticated_command(&config_home, &server)
        .args(["incidents", "list", "--limit", "1"])
        .assert()
        .code(6)
        .stderr(predicate::str::contains("rate limit"));
}