busbar-sf-api 0.0.3

Salesforce API client library for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
//! REST API integration tests using SF_AUTH_URL.

use super::common::get_credentials;
use busbar_sf_auth::Credentials;
use busbar_sf_rest::{CompositeRequest, CompositeSubrequest, QueryBuilder, SalesforceRestClient};
use serde::{Deserialize, Serialize};

// ============================================================================
// Test Data Setup (runs first via CI "Setup test data" step)
// ============================================================================

/// Creates test Account records used by search and other tests.
/// Called explicitly by CI before the main test run to ensure data exists.
#[tokio::test]
async fn test_00_setup_test_data() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let ids = super::common::ensure_test_accounts(&client).await;
    assert!(
        !ids.is_empty(),
        "Should have created or found test accounts"
    );
    println!("Test data setup: {} accounts ready", ids.len());
}

// ============================================================================
// REST API - Comprehensive Tests
// ============================================================================

#[tokio::test]
async fn test_rest_composite_api() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let composite_request = CompositeRequest {
        all_or_none: true,
        collate_subrequests: false,
        subrequests: vec![
            CompositeSubrequest {
                method: "POST".to_string(),
                url: format!("/services/data/v{}/sobjects/Account", creds.api_version()),
                reference_id: "NewAccount".to_string(),
                body: Some(serde_json::json!({
                    "Name": format!(
                        "Composite Test Account {}",
                        chrono::Utc::now().timestamp_millis()
                    )
                })),
            },
            CompositeSubrequest {
                method: "GET".to_string(),
                url: format!(
                    "/services/data/v{}/sobjects/Account/@{{NewAccount.id}}",
                    creds.api_version()
                ),
                reference_id: "GetNewAccount".to_string(),
                body: None,
            },
        ],
    };

    let response = client
        .composite(&composite_request)
        .await
        .expect("Composite request should succeed");

    assert_eq!(response.responses.len(), 2, "Should have 2 sub-responses");

    if let Some(first_response) = response.responses.first() {
        if let Some(id) = first_response.body.get("id").and_then(|v| v.as_str()) {
            let _ = client.delete("Account", id).await;
        }
    }
}

#[tokio::test]
async fn test_rest_search_sosl() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let search_query = "FIND {test*} IN NAME FIELDS RETURNING Account(Id, Name), Contact(Id, Name)";
    let result = client.search::<serde_json::Value>(search_query).await;

    assert!(result.is_ok(), "SOSL search should succeed");
}

#[tokio::test]
async fn test_rest_batch_operations() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let test_accounts = vec![
        serde_json::json!({
            "Name": format!("Batch Test 1 {}", chrono::Utc::now().timestamp_millis())
        }),
        serde_json::json!({
            "Name": format!("Batch Test 2 {}", chrono::Utc::now().timestamp_millis())
        }),
        serde_json::json!({
            "Name": format!("Batch Test 3 {}", chrono::Utc::now().timestamp_millis())
        }),
    ];

    let create_results = client
        .create_multiple("Account", &test_accounts, false)
        .await
        .expect("create_multiple should succeed");

    assert_eq!(create_results.len(), 3, "Should create 3 accounts");

    let ids: Vec<String> = create_results.iter().filter_map(|r| r.id.clone()).collect();
    assert_eq!(ids.len(), 3, "Should have 3 account IDs");

    let id_refs: Vec<&str> = ids.iter().map(|s| s.as_str()).collect();
    let get_results: Vec<serde_json::Value> = client
        .get_multiple("Account", &id_refs, &["Id", "Name"])
        .await
        .expect("get_multiple should succeed");

    assert_eq!(get_results.len(), 3, "Should retrieve 3 accounts");

    let updates: Vec<(String, serde_json::Value)> = ids
        .iter()
        .map(|id| {
            (
                id.clone(),
                serde_json::json!({
                    "Description": "Updated by batch test"
                }),
            )
        })
        .collect();

    let update_results = client
        .update_multiple("Account", &updates, false)
        .await
        .expect("update_multiple should succeed");

    assert_eq!(update_results.len(), 3, "Should update 3 accounts");

    let delete_results = client
        .delete_multiple(&id_refs, false)
        .await
        .expect("delete_multiple should succeed");

    assert_eq!(delete_results.len(), 3, "Should delete 3 accounts");
}

#[tokio::test]
async fn test_rest_query_pagination() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let result = client
        .query::<serde_json::Value>("SELECT Id, Name FROM Account LIMIT 5")
        .await
        .expect("Query should succeed");

    assert!(
        result.done || result.next_records_url.is_some(),
        "Should indicate completion or pagination"
    );

    let all_records: Vec<serde_json::Value> = client
        .query_all("SELECT Id, Name FROM Account LIMIT 100")
        .await
        .expect("query_all should succeed");

    assert!(all_records.len() <= 100, "Should respect LIMIT");
}

#[tokio::test]
async fn test_rest_upsert_operation() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let unique_id = format!("TEST-{}", chrono::Utc::now().timestamp_millis());

    // The external ID field value goes in the URL path, NOT in the body.
    // Including it in the body causes INVALID_FIELD error.
    let account_data = serde_json::json!({
        "Name": format!("Upsert Test {}", unique_id)
    });

    let upsert_result = client
        .upsert(
            "Account",
            "BusbarIntTestExtId__c",
            &unique_id,
            &account_data,
        )
        .await
        .expect("First upsert should succeed");

    assert!(upsert_result.created, "First upsert should create record");
    let account_id = upsert_result.id.clone();

    let updated_data = serde_json::json!({
        "Name": format!("Upsert Test Updated {}", unique_id)
    });

    let upsert_result2 = client
        .upsert(
            "Account",
            "BusbarIntTestExtId__c",
            &unique_id,
            &updated_data,
        )
        .await
        .expect("Second upsert should succeed");

    assert!(
        !upsert_result2.created,
        "Second upsert should update record"
    );
    assert_eq!(upsert_result2.id, account_id, "Should be same account ID");

    let _ = client.delete("Account", &account_id).await;
}

// ============================================================================
// QueryBuilder Security Tests
// ============================================================================

#[tokio::test]
async fn test_query_builder_injection_prevention() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let malicious_input = "Test' OR '1'='1";

    let result: Result<Vec<serde_json::Value>, _> = QueryBuilder::new("Account")
        .expect("QueryBuilder creation should succeed")
        .select(&["Id", "Name"])
        .where_eq("Name", malicious_input)
        .expect("where_eq should succeed")
        .limit(10)
        .execute(&client)
        .await;

    assert!(result.is_ok(), "Query should succeed with escaped input");
    let accounts = result.unwrap();

    assert_eq!(
        accounts.len(),
        0,
        "Should not find any accounts with malicious input"
    );
}

#[tokio::test]
async fn test_query_builder_like_escaping() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let pattern = "test%";

    let result: Result<Vec<serde_json::Value>, _> = QueryBuilder::new("Account")
        .expect("QueryBuilder creation should succeed")
        .select(&["Id", "Name"])
        .where_like("Name", pattern)
        .expect("where_like should succeed")
        .limit(10)
        .execute(&client)
        .await;

    assert!(result.is_ok(), "LIKE query should succeed");
}

// ============================================================================
// Error Handling Tests
// ============================================================================

#[tokio::test]
async fn test_rest_error_invalid_field_query() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let result = client
        .query::<serde_json::Value>("SELECT Id, InvalidFieldName123 FROM Account")
        .await;

    assert!(result.is_err(), "Query with invalid field should fail");
}

#[tokio::test]
async fn test_rest_error_invalid_sobject_describe() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let result = client.describe_sobject("NonExistentObject__c").await;

    assert!(
        result.is_err(),
        "Describing non-existent object should fail"
    );
}

#[tokio::test]
async fn test_rest_error_invalid_record_id_get() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let result: Result<serde_json::Value, _> = client.get("Account", "bad-id", None).await;

    assert!(result.is_err(), "Getting non-existent record should fail");
}

#[tokio::test]
async fn test_rest_error_invalid_sobject_create() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let result = client
        .create(
            "Account'; DROP TABLE--",
            &serde_json::json!({"Name": "Bad"}),
        )
        .await;

    assert!(result.is_err(), "Create with invalid SObject should fail");
}

#[tokio::test]
async fn test_rest_error_invalid_id_update_delete() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let update_result = client
        .update("Account", "bad-id", &serde_json::json!({"Name": "Bad"}))
        .await;

    assert!(update_result.is_err(), "Update with invalid ID should fail");

    let delete_result = client.delete("Account", "bad-id").await;

    assert!(delete_result.is_err(), "Delete with invalid ID should fail");
}

#[tokio::test]
async fn test_rest_error_invalid_upsert_field() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let result = client
        .upsert(
            "Account",
            "AccountNumber; DROP",
            "bad",
            &serde_json::json!({"Name": "Bad"}),
        )
        .await;

    assert!(result.is_err(), "Upsert with invalid field should fail");
}

#[tokio::test]
async fn test_rest_error_invalid_sosl() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let result = client
        .search::<serde_json::Value>("FIND {test} RETURNING")
        .await;

    assert!(result.is_err(), "Invalid SOSL should fail");
}

#[tokio::test]
async fn test_rest_error_batch_invalid_input() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let create_result = client
        .create_multiple("Account; DROP", &Vec::<serde_json::Value>::new(), false)
        .await;

    assert!(
        create_result.is_err(),
        "create_multiple invalid sobject should fail"
    );

    let update_result = client
        .update_multiple(
            "Account",
            &[("bad-id".to_string(), serde_json::json!({"Name": "Bad"}))],
            false,
        )
        .await;

    assert!(
        update_result.is_err(),
        "update_multiple invalid ID should fail"
    );

    let delete_result = client.delete_multiple(&["bad-id"], false).await;

    assert!(
        delete_result.is_err(),
        "delete_multiple invalid ID should fail"
    );

    let get_result: Result<Vec<serde_json::Value>, _> =
        client.get_multiple("Account", &["bad-id"], &["Id"]).await;

    assert!(get_result.is_err(), "get_multiple invalid ID should fail");
}

#[tokio::test]
async fn test_rest_composite_error_subrequest() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let composite_request = CompositeRequest {
        all_or_none: false,
        collate_subrequests: false,
        subrequests: vec![CompositeSubrequest {
            method: "GET".to_string(),
            url: format!("/services/data/v{}/sobjects/Nope__c", creds.api_version()),
            reference_id: "BadRequest".to_string(),
            body: None,
        }],
    };

    let response = client
        .composite(&composite_request)
        .await
        .expect("Composite request should succeed at transport level");

    let sub = response
        .responses
        .first()
        .expect("Should have one response");
    assert!(sub.http_status_code >= 400, "Subrequest should error");
}

// ============================================================================
// Security Tests
// ============================================================================

#[tokio::test]
async fn test_credentials_redaction() {
    let creds = get_credentials().await;

    let debug_output = format!("{:?}", creds);

    assert!(
        debug_output.contains("[REDACTED]") || !debug_output.contains(creds.access_token()),
        "Debug output should not contain actual token"
    );
}

#[tokio::test]
async fn test_client_debug_redaction() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let debug_output = format!("{:?}", client);

    assert!(
        !debug_output.contains(creds.access_token()),
        "Client debug output should not contain actual token"
    );
}

// ============================================================================
// Type-Safe Pattern Tests
// ============================================================================

#[derive(Debug, Clone, Serialize, Deserialize)]
struct TestAccount {
    #[serde(rename = "Id", skip_serializing_if = "Option::is_none")]
    id: Option<String>,
    #[serde(rename = "Name")]
    name: String,
    #[serde(rename = "Industry", skip_serializing_if = "Option::is_none")]
    industry: Option<String>,
}

#[tokio::test]
async fn test_type_safe_crud() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let account = TestAccount {
        id: None,
        name: format!("Type Safe Test {}", chrono::Utc::now().timestamp_millis()),
        industry: Some("Technology".to_string()),
    };

    let id = client
        .create("Account", &account)
        .await
        .expect("Create should succeed");

    let retrieved: TestAccount = client
        .get("Account", &id, Some(&["Id", "Name", "Industry"]))
        .await
        .expect("Get should succeed");

    assert_eq!(retrieved.name, account.name);
    assert_eq!(retrieved.industry, account.industry);

    let update_data = serde_json::json!({
        "Industry": "Finance"
    });

    client
        .update("Account", &id, &update_data)
        .await
        .expect("Update should succeed");

    client
        .delete("Account", &id)
        .await
        .expect("Delete should succeed");
}

#[tokio::test]
async fn test_type_safe_query() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let accounts: Vec<TestAccount> = client
        .query_all("SELECT Id, Name, Industry FROM Account LIMIT 10")
        .await
        .expect("Query should succeed");

    for account in &accounts {
        assert!(account.id.is_some(), "Account should have ID");
        assert!(!account.name.is_empty(), "Account should have name");
    }
}

// ============================================================================
// Layout API Tests
// ============================================================================

#[tokio::test]
async fn test_rest_describe_layouts() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let result = client
        .describe_layouts("Account")
        .await
        .expect("describe_layouts should succeed for Account");

    assert!(
        result.is_object(),
        "Layout response should be a JSON object"
    );
    assert!(
        result.get("layouts").is_some(),
        "Response should contain layouts"
    );
}

#[tokio::test]
async fn test_rest_describe_layouts_contact() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let result = client
        .describe_layouts("Contact")
        .await
        .expect("describe_layouts should succeed for Contact");

    assert!(
        result.is_object(),
        "Layout response should be a JSON object"
    );
}

#[tokio::test]
async fn test_rest_describe_approval_layouts() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let result = client
        .describe_approval_layouts("Account")
        .await
        .expect("describe_approval_layouts should succeed");

    assert!(
        result.is_object(),
        "Approval layout response should be a JSON object"
    );
    assert!(
        result.get("approvalLayouts").is_some(),
        "Response should contain approvalLayouts"
    );
}

#[tokio::test]
async fn test_rest_describe_compact_layouts() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let result = client
        .describe_compact_layouts("Account")
        .await
        .expect("describe_compact_layouts should succeed");

    assert!(
        result.is_object(),
        "Compact layout response should be a JSON object"
    );
    assert!(
        result.get("compactLayouts").is_some(),
        "Response should contain compactLayouts"
    );
}

#[tokio::test]
async fn test_rest_describe_global_publisher_layouts() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let result = client
        .describe_global_publisher_layouts()
        .await
        .expect("describe_global_publisher_layouts should succeed");

    assert!(
        result.is_object(),
        "Global publisher layout response should be a JSON object"
    );
    assert!(
        result.get("layouts").is_some(),
        "Response should contain layouts"
    );
}

#[tokio::test]
async fn test_rest_describe_named_layout() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    // Named layouts are alternate layout types (e.g., "UserAlt"), not page layout names.
    // The User object has the well-known "UserAlt" named layout in all orgs.
    let named_result = client
        .describe_named_layout("User", "UserAlt")
        .await
        .expect("describe_named_layout should succeed for User/UserAlt");

    assert!(
        named_result.is_object(),
        "Named layout response should be a JSON object"
    );
}

// ============================================================================
// Layout API Error Tests
// ============================================================================

#[tokio::test]
async fn test_rest_describe_layouts_invalid_sobject() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let result = client.describe_layouts("InvalidObject__c__c").await;

    assert!(
        result.is_err(),
        "describe_layouts should fail for invalid SObject"
    );
}

#[tokio::test]
async fn test_rest_describe_layouts_injection_attempt() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let result = client.describe_layouts("Account'; DROP TABLE--").await;

    assert!(
        result.is_err(),
        "describe_layouts should reject SQL injection attempts"
    );
}

#[tokio::test]
async fn test_rest_describe_named_layout_special_chars() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    // Test that special characters in layout names are properly URL-encoded
    let result = client
        .describe_named_layout("Account", "Layout With Spaces")
        .await;

    // This might fail if the layout doesn't exist, but should not fail due to URL encoding
    // The error should be a 404 or similar, not a URL parsing error
    if let Err(e) = result {
        let error_msg = format!("{:?}", e);
        assert!(
            !error_msg.contains("url") || !error_msg.contains("parse"),
            "Should not fail due to URL parsing issues"
        );
    }
}

// ============================================================================
// Composite Graph API Tests (PR #51)
// ============================================================================

#[tokio::test]
async fn test_rest_composite_graph_api() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let request = busbar_sf_rest::CompositeGraphRequest {
        graphs: vec![busbar_sf_rest::GraphRequest {
            graph_id: "graph1".to_string(),
            composite_request: vec![busbar_sf_rest::CompositeSubrequest {
                method: "POST".to_string(),
                url: format!("/services/data/v{}/sobjects/Account", creds.api_version()),
                reference_id: "NewAccount".to_string(),
                body: Some(serde_json::json!({
                    "Name": format!("Graph Test Account {}", chrono::Utc::now().timestamp_millis())
                })),
            }],
        }],
    };

    let response = client
        .composite_graph(&request)
        .await
        .expect("Composite graph should succeed");

    assert!(!response.graphs.is_empty(), "Should have graph responses");
    let graph = &response.graphs[0];
    assert_eq!(graph.graph_id, "graph1");

    // Clean up
    if let Some(resp) = graph.graph_response.responses.first() {
        if let Some(id) = resp.body.get("id").and_then(|v| v.as_str()) {
            let _ = client.delete("Account", id).await;
        }
    }
}

// ============================================================================
// Advanced Search Tests (PR #52)
// ============================================================================

#[tokio::test]
async fn test_parameterized_search() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    // Ensure test data exists (search index may not include these yet,
    // but the API call should succeed regardless)
    super::common::ensure_test_accounts(&client).await;

    let request = busbar_sf_rest::ParameterizedSearchRequest {
        q: "BusbarIntTest*".to_string(),
        fields: None,
        sobjects: Some(vec![busbar_sf_rest::SearchSObjectSpec {
            name: "Account".to_string(),
            fields: Some(vec!["Id".into(), "Name".into()]),
            where_clause: None,
            limit: Some(5),
        }]),
        overall_limit: Some(10),
        offset: None,
        spell_correction: None,
    };

    let result = client.parameterized_search(&request).await;
    assert!(
        result.is_ok(),
        "Parameterized search should succeed: {:?}",
        result.err()
    );
}

#[tokio::test]
async fn test_search_scope_order() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let result = client.search_scope_order().await;
    assert!(result.is_ok(), "search_scope_order should succeed");
}

#[tokio::test]
async fn test_search_result_layouts() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let result = client.search_result_layouts(&["Account", "Contact"]).await;
    assert!(
        result.is_ok(),
        "search_result_layouts should succeed: {:?}",
        result.err()
    );
}

#[tokio::test]
async fn test_search_suggestions() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    // Ensure test accounts exist for suggestions to find
    super::common::ensure_test_accounts(&client).await;

    let result = client.search_suggestions("Busbar", "Account").await;
    assert!(
        result.is_ok(),
        "search_suggestions should succeed: {:?}",
        result.err()
    );
}

// ============================================================================
// Quick Actions Tests (PR #53)
// ============================================================================

#[tokio::test]
async fn test_quick_actions_list() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let result = client.list_quick_actions("Account").await;
    assert!(result.is_ok(), "list_quick_actions should succeed");
}

#[tokio::test]
async fn test_quick_actions_describe() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    // First try SObject-level quick actions
    let actions = client
        .list_quick_actions("Account")
        .await
        .expect("list_quick_actions should succeed");

    // Try each action until we find one describable at the SObject level.
    // Global actions return NOT_FOUND when described at the SObject level.
    for action in &actions {
        let result = client.describe_quick_action("Account", &action.name).await;
        match result {
            Ok(describe) => {
                assert_eq!(describe.name, action.name);
                return; // Success — found an SObject-level action
            }
            Err(e) if e.to_string().contains("NOT_FOUND") => continue,
            Err(e) => {
                panic!(
                    "describe_quick_action failed for {} with unexpected error: {}",
                    action.name, e
                );
            }
        }
    }

    // All Account quick actions were global (NOT_FOUND at SObject level).
    // Fall back to global quick actions — these always exist in any org.
    let global_actions = client
        .list_global_quick_actions()
        .await
        .expect("list_global_quick_actions should succeed");
    assert!(
        !global_actions.is_empty(),
        "Org should have at least one global quick action"
    );

    let described = client
        .describe_global_quick_action(&global_actions[0].name)
        .await
        .expect("describe_global_quick_action should succeed");
    assert_eq!(described.name, global_actions[0].name);
}

#[tokio::test]
async fn test_quick_actions_invoke() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    // Create a test Account to invoke quick actions against
    let account_id = client
        .create(
            "Account",
            &serde_json::json!({"Name": format!("QA Test {}", chrono::Utc::now().timestamp_millis())}),
        )
        .await
        .expect("Account creation should succeed");

    let actions = client
        .list_quick_actions("Account")
        .await
        .expect("list_quick_actions should succeed");

    // Try to invoke any available quick action. Even if it fails with
    // REQUIRED_FIELD_MISSING, that's a valid Salesforce response proving our client works.
    let mut invoked = false;
    for action in &actions {
        // Try a LogACall-type action first (fewest required fields)
        if action.action_type != "LogACall" && action.action_type != "Update" {
            continue;
        }
        let body = match action.action_type.as_str() {
            "LogACall" => serde_json::json!({"record": {"Subject": "Test Call"}}),
            "Update" => serde_json::json!({"record": {}}), // Update with no changes
            _ => continue,
        };
        let result = client
            .invoke_quick_action("Account", &action.name, &body)
            .await;
        match result {
            Ok(r) => {
                // Success or partial success — our client works
                assert!(
                    r.success || r.context_id.is_some(),
                    "Quick action result should have success or contextId"
                );
                invoked = true;
                break;
            }
            Err(e) => {
                let msg = e.to_string();
                // These are valid Salesforce responses (our client serialized correctly)
                if msg.contains("REQUIRED_FIELD_MISSING")
                    || msg.contains("INVALID_FIELD")
                    || msg.contains("NOT_FOUND")
                {
                    invoked = true;
                    break;
                }
                // Unexpected error — try next action
                continue;
            }
        }
    }

    // Clean up
    let _ = client.delete("Account", &account_id).await;

    assert!(
        invoked,
        "Should have attempted at least one quick action invoke"
    );
}

#[tokio::test]
async fn test_quick_actions_error_invalid_sobject() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let result = client.list_quick_actions("Bad'; DROP--").await;
    assert!(
        result.is_err(),
        "list_quick_actions with invalid SObject should fail"
    );
}

// ============================================================================
// List Views Tests (PR #53)
// ============================================================================

#[tokio::test]
async fn test_list_views_list() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    // Requires BusbarIntTest_AllAccounts list view deployed by setup-scratch-org
    let collection = client
        .list_views("Account")
        .await
        .expect("list_views should succeed for Account");
    assert!(
        !collection.listviews.is_empty(),
        "Account should have list views (deployed by scripts/setup-scratch-org). \
         Run: cargo run --bin setup-scratch-org"
    );

    let first = &collection.listviews[0];
    assert!(!first.id.is_empty(), "List view should have an ID");
    assert!(!first.label.is_empty(), "List view should have a label");
}

#[tokio::test]
async fn test_list_views_get() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let collection = client
        .list_views("Account")
        .await
        .expect("list_views should succeed");

    let lv = collection.listviews.first().expect(
        "Account should have list views (deployed by setup-scratch-org). \
         Run: cargo run --bin setup-scratch-org",
    );
    let view = client
        .get_list_view("Account", &lv.id)
        .await
        .expect("get_list_view should succeed");
    assert_eq!(view.id, lv.id);
}

#[tokio::test]
async fn test_list_views_describe() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let collection = client
        .list_views("Account")
        .await
        .expect("list_views should succeed");

    if let Some(lv) = collection.listviews.first() {
        let describe = client
            .describe_list_view("Account", &lv.id)
            .await
            .unwrap_or_else(|e| panic!("describe_list_view failed for ID {}: {e}", lv.id));
        assert!(!describe.columns.is_empty(), "Should have columns");
    } else {
        panic!(
            "Account should have list views (deployed by setup-scratch-org). \
             Run: cargo run --bin setup-scratch-org"
        );
    }
}

#[tokio::test]
async fn test_list_views_execute() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let collection = client
        .list_views("Account")
        .await
        .expect("list_views should succeed");

    let lv = collection.listviews.first().expect(
        "Account should have list views (deployed by setup-scratch-org). \
         Run: cargo run --bin setup-scratch-org",
    );
    let result: busbar_sf_rest::ListViewResult<serde_json::Value> = client
        .execute_list_view("Account", &lv.id)
        .await
        .expect("execute_list_view should succeed");
    assert!(result.done, "List view execution should complete");
}

#[tokio::test]
async fn test_list_views_error_invalid_id() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let result = client.get_list_view("Account", "bad-id").await;
    assert!(result.is_err(), "get_list_view with invalid ID should fail");
}

// ============================================================================
// Process Rules Tests (PR #53)
// ============================================================================

#[tokio::test]
async fn test_process_rules_list_all() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let result = client.list_process_rules().await;
    assert!(
        result.is_ok(),
        "list_process_rules should succeed: {:?}",
        result.err()
    );
}

#[tokio::test]
async fn test_process_rules_list_for_sobject() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let rules = client
        .list_process_rules_for_sobject("Account")
        .await
        .expect("list_process_rules_for_sobject should succeed");
    assert!(!rules.is_empty(), "Should have process rules for Account");
}

#[tokio::test]
async fn test_process_rules_trigger() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    // Name must start with "BusbarIntTest_ProcessRule" to match the deployed workflow rule
    let test_name = format!(
        "BusbarIntTest_ProcessRule_{}",
        chrono::Utc::now().timestamp_millis()
    );
    let account_id = client
        .create("Account", &serde_json::json!({"Name": test_name}))
        .await
        .expect("Account creation should succeed");

    let request = busbar_sf_rest::ProcessRuleRequest {
        context_ids: vec![account_id.clone()],
    };

    let result = client
        .trigger_process_rules(&request)
        .await
        .expect("trigger_process_rules should succeed");
    assert!(result.success, "Process rule trigger should succeed");

    let _ = client.delete("Account", &account_id).await;
}

#[tokio::test]
async fn test_process_rules_error_invalid_id() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let request = busbar_sf_rest::ProcessRuleRequest {
        context_ids: vec!["bad-id-not-valid".to_string()],
    };

    let result = client.trigger_process_rules(&request).await;
    assert!(
        result.is_err(),
        "trigger_process_rules with invalid ID should fail"
    );
}

// ============================================================================
// Approvals Tests (PR #53)
// ============================================================================

#[tokio::test]
async fn test_approvals_list_pending() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let result = client.list_pending_approvals().await;
    assert!(
        result.is_ok(),
        "list_pending_approvals should succeed: {:?}",
        result.err()
    );
}

#[tokio::test]
async fn test_approvals_submit() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let test_name = format!("Approval Test {}", chrono::Utc::now().timestamp_millis());
    let account_id = client
        .create("Account", &serde_json::json!({"Name": test_name}))
        .await
        .expect("Account creation should succeed");

    let request = busbar_sf_rest::ApprovalRequest {
        action_type: busbar_sf_rest::ApprovalActionType::Submit,
        context_id: account_id.clone(),
        context_actor_id: None,
        comments: Some("Integration test submission".to_string()),
        next_approver_ids: None,
        process_definition_name_or_id: Some("BusbarIntTest_Approval".to_string()),
        skip_entry_criteria: Some(true),
    };

    let result = client
        .submit_approval(&request)
        .await
        .expect("submit_approval should succeed");
    assert!(result.success, "Approval submission should succeed");

    let _ = client.delete("Account", &account_id).await;
}

#[tokio::test]
async fn test_approvals_error_invalid_id() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let request = busbar_sf_rest::ApprovalRequest {
        action_type: busbar_sf_rest::ApprovalActionType::Submit,
        context_id: "bad-id-not-valid".to_string(),
        context_actor_id: None,
        comments: None,
        next_approver_ids: None,
        process_definition_name_or_id: None,
        skip_entry_criteria: None,
    };

    let result = client.submit_approval(&request).await;
    // Should fail with an invalid context ID
    assert!(
        result.is_err(),
        "submit_approval with invalid ID should fail"
    );
}

// ============================================================================
// Invocable Actions Tests (PR #53)
// ============================================================================

#[tokio::test]
async fn test_invocable_actions_list_standard() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    // Standard actions are returned as a flat list from /actions/standard
    let collection = client
        .list_standard_actions()
        .await
        .expect("list_standard_actions should succeed");
    assert!(
        !collection.actions.is_empty(),
        "Should have standard actions available"
    );
    println!("Standard actions: {} actions", collection.actions.len());
}

#[tokio::test]
async fn test_invocable_actions_describe_standard() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    // List standard actions, then describe the first one
    let collection = client
        .list_standard_actions()
        .await
        .expect("list_standard_actions should succeed");
    assert!(
        !collection.actions.is_empty(),
        "Should have standard actions to describe"
    );

    let action = &collection.actions[0];
    let describe = client
        .describe_standard_action(&action.name)
        .await
        .expect("describe_standard_action should succeed");
    assert_eq!(describe.name, action.name);
}

#[tokio::test]
async fn test_invocable_actions_invoke_standard() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    // Use chatterPost — a well-known standard action with known required inputs.
    // First describe it to verify the expected input parameters.
    let describe = client
        .describe_standard_action("chatterPost")
        .await
        .expect("describe_standard_action(chatterPost) should succeed");
    assert_eq!(describe.name, "chatterPost");

    let required_inputs: Vec<&str> = describe
        .inputs
        .iter()
        .filter(|p| p.required)
        .map(|p| p.name.as_str())
        .collect();
    assert!(
        required_inputs.contains(&"text") && required_inputs.contains(&"subjectNameOrId"),
        "chatterPost should require 'text' and 'subjectNameOrId', got: {:?}",
        required_inputs
    );

    // Get the current user's ID for subjectNameOrId
    let users: Vec<serde_json::Value> = client
        .query_all("SELECT Id FROM User WHERE IsActive = true LIMIT 1")
        .await
        .expect("User query should succeed");
    let user_id = users[0]
        .get("Id")
        .and_then(|v| v.as_str())
        .expect("Should have User Id");

    let request = busbar_sf_rest::InvocableActionRequest {
        inputs: vec![serde_json::json!({
            "text": "Integration test post",
            "subjectNameOrId": user_id
        })],
    };

    let results = client
        .invoke_standard_action("chatterPost", &request)
        .await
        .expect("invoke_standard_action(chatterPost) should succeed");
    assert!(!results.is_empty(), "Should have at least one result");
    assert!(
        results[0].is_success,
        "chatterPost should succeed: {:?}",
        results[0].errors
    );
}

#[tokio::test]
async fn test_invocable_actions_list_custom_types() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let types = client
        .list_custom_action_types()
        .await
        .expect("list_custom_action_types should succeed");
    // Custom action types may be empty on a fresh scratch org — that's valid
    println!("Custom action type categories: {}", types.len());
}

#[tokio::test]
async fn test_invocable_actions_describe_custom() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let types = client
        .list_custom_action_types()
        .await
        .expect("list_custom_action_types should succeed");

    for action_type_name in types.keys() {
        let collection = client
            .list_custom_actions(action_type_name)
            .await
            .expect("list_custom_actions should succeed");
        if let Some(action) = collection.actions.first() {
            let describe = client
                .describe_custom_action(action_type_name, &action.name)
                .await
                .expect("describe_custom_action should succeed");
            assert_eq!(describe.name, action.name);
            return;
        }
    }
    // No custom actions is valid on a fresh scratch org
    println!("No custom actions found — scratch org has no custom actions deployed");
}

#[tokio::test]
async fn test_invocable_actions_invoke_custom() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let types = client
        .list_custom_action_types()
        .await
        .expect("list_custom_action_types should succeed");

    for action_type_name in types.keys() {
        let collection = client
            .list_custom_actions(action_type_name)
            .await
            .expect("list_custom_actions should succeed");
        for action in &collection.actions {
            // Describe the action to learn its required inputs
            let describe = client
                .describe_custom_action(action_type_name, &action.name)
                .await
                .expect("describe_custom_action should succeed");

            // Build inputs from required parameters using type-appropriate defaults
            let mut input = serde_json::Map::new();
            let mut has_unsatisfiable_input = false;
            for param in &describe.inputs {
                if !param.required {
                    continue;
                }
                match param.param_type.as_str() {
                    "STRING" | "TEXTAREA" => {
                        input.insert(param.name.clone(), serde_json::json!("test"));
                    }
                    "BOOLEAN" => {
                        input.insert(param.name.clone(), serde_json::json!(false));
                    }
                    "NUMBER" | "INTEGER" | "DOUBLE" | "DECIMAL" | "CURRENCY" => {
                        input.insert(param.name.clone(), serde_json::json!(0));
                    }
                    _ => {
                        // REFERENCE, PICKLIST, etc. require org-specific values
                        has_unsatisfiable_input = true;
                        break;
                    }
                }
            }
            if has_unsatisfiable_input {
                continue; // Try next action
            }

            let request = busbar_sf_rest::InvocableActionRequest {
                inputs: vec![serde_json::Value::Object(input)],
            };

            // Invoke the action — some custom actions (e.g., Flow-based) may return
            // HTTP 400 even with valid inputs if they require specific org state.
            // Both success and Salesforce-level errors prove our client works.
            match client
                .invoke_custom_action(action_type_name, &action.name, &request)
                .await
            {
                Ok(results) => {
                    assert!(!results.is_empty(), "Should have at least one result");
                    return;
                }
                Err(e) => {
                    let msg = e.to_string();
                    // These are valid Salesforce responses (our serialization worked)
                    if msg.contains("UNKNOWN_EXCEPTION")
                        || msg.contains("INVALID_INPUT")
                        || msg.contains("flow interview")
                        || msg.contains("400")
                    {
                        // Action invoked but failed server-side — still a valid test
                        return;
                    }
                    // Try next action for unexpected errors
                    continue;
                }
            }
        }
    }
    // No custom actions with simple inputs is valid — all CRUD/list/describe calls above
    // already exercised the API. Only panic if there were NO custom actions at all.
    let total_actions: usize = types.len();
    if total_actions == 0 {
        // No custom action types at all — that's fine for a scratch org
        return;
    }
    // Had custom actions but all require REFERENCE-type inputs we can't satisfy
    // The list/describe calls above already tested the API, so this is acceptable
}

#[tokio::test]
async fn test_invocable_actions_error_invalid_name() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let result = client.describe_standard_action("Bad'; DROP--").await;
    assert!(
        result.is_err(),
        "describe_standard_action with invalid name should fail"
    );
}

// ============================================================================
// Consent API Tests (PR #54)
// ============================================================================

#[tokio::test]
async fn test_consent_read() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    // Query for a real Account ID to use in consent check
    let accounts: Vec<serde_json::Value> = client
        .query_all("SELECT Id FROM Account WHERE Name LIKE 'BusbarIntTest_%' LIMIT 1")
        .await
        .expect("Account query should succeed");
    assert!(
        !accounts.is_empty(),
        "Should have at least one BusbarIntTest account (created by setup-scratch-org)"
    );
    let account_id = accounts[0]["Id"].as_str().expect("Account should have Id");

    let _response = client
        .read_consent("email", &[account_id])
        .await
        .expect("read_consent should succeed");
}

// ============================================================================
// Knowledge Management Tests (PR #54)
// ============================================================================

#[tokio::test]
async fn test_knowledge_settings() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let settings = client
        .knowledge_settings()
        .await
        .expect("knowledge_settings should succeed");
    // Just verify deserialization works; knowledge_enabled may be false in some orgs
    if settings.knowledge_enabled {
        // If Knowledge is enabled, languages might be populated
        assert!(settings.default_language.is_some() || settings.languages.is_empty());
    }
}

#[tokio::test]
async fn test_data_category_groups() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    // The support/dataCategoryGroups endpoint requires Knowledge to be fully
    // configured with data category user visibility. In scratch orgs without
    // this config, the endpoint returns NOT_FOUND.
    let result = client.data_category_groups(None).await;
    match result {
        Ok(groups) => {
            // If the endpoint works, verify response is valid
            assert!(
                !groups.category_groups.is_empty(),
                "Should have data category groups when endpoint is available"
            );
        }
        Err(e) => {
            let err_str = e.to_string();
            assert!(
                err_str.contains("NOT_FOUND"),
                "Expected NOT_FOUND when Knowledge data categories not configured, got: {err_str}"
            );
        }
    }
}

// ============================================================================
// User Password Tests (PR #54)
// ============================================================================

#[tokio::test]
async fn test_user_password_status() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    // Query for current user's ID
    let users: Vec<serde_json::Value> = client
        .query_all("SELECT Id FROM User WHERE IsActive = true LIMIT 1")
        .await
        .expect("User query should succeed");

    let user = users.first().expect("Should have at least one active user");
    let user_id = user
        .get("Id")
        .and_then(|v| v.as_str())
        .expect("User should have an Id field");

    let _status = client
        .get_user_password_status(user_id)
        .await
        .expect("get_user_password_status should succeed");
}

// ============================================================================
// Standalone REST Endpoint Tests (PR #55)
// ============================================================================

#[tokio::test]
async fn test_rest_tabs() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let tabs = client.tabs().await.expect("tabs should succeed");
    assert!(!tabs.is_empty(), "Should have at least one tab");
}

#[tokio::test]
async fn test_rest_theme() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let theme = client.theme().await.expect("theme should succeed");
    assert!(theme.is_object(), "Theme should be a JSON object");
}

#[tokio::test]
async fn test_rest_recent_items() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let _items = client
        .recent_items()
        .await
        .expect("recent_items should succeed");
}

#[tokio::test]
async fn test_rest_relevant_items() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let _items = client
        .relevant_items()
        .await
        .expect("relevant_items should succeed");
}

#[tokio::test]
async fn test_rest_app_menu() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let result = client.app_menu("AppSwitcher").await;
    assert!(result.is_ok(), "app_menu should succeed for AppSwitcher");
}

#[tokio::test]
async fn test_rest_lightning_usage() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    // Lightning Usage API may not be available in all orgs (e.g., scratch orgs).
    // Test that we either get valid data OR a proper NOT_FOUND error.
    match client.lightning_usage().await {
        Ok(usage) => {
            assert!(
                usage.is_object() || usage.is_array(),
                "Lightning usage should return JSON object or array"
            );
        }
        Err(e) => {
            let msg = e.to_string();
            assert!(
                msg.contains("NOT_FOUND") || msg.contains("404"),
                "Lightning usage error should be NOT_FOUND in unsupported orgs, got: {msg}"
            );
        }
    }
}

// ============================================================================
// Incremental Sync Tests (PR #49)
// ============================================================================

#[tokio::test]
async fn test_get_deleted_records() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    // Create and delete a test account
    let test_name = format!("Delete Test {}", chrono::Utc::now().timestamp_millis());
    let account_id = client
        .create("Account", &serde_json::json!({"Name": test_name}))
        .await
        .expect("Account creation should succeed");

    client
        .delete("Account", &account_id)
        .await
        .expect("Delete should succeed");

    tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;

    // Use a short window (5 minutes) — on new scratch orgs, the replication
    // date starts at org creation time, so "now - 1 day" is before the org existed.
    let now = chrono::Utc::now();
    let start = (now - chrono::Duration::minutes(5)).to_rfc3339();
    let end = now.to_rfc3339();

    let result = client
        .get_deleted("Account", &start, &end)
        .await
        .expect("get_deleted should succeed");

    assert!(!result.earliest_date_available.is_empty());
    assert!(!result.latest_date_covered.is_empty());
}

#[tokio::test]
async fn test_get_updated_records() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let test_name = format!("Update Test {}", chrono::Utc::now().timestamp_millis());
    let account_id = client
        .create("Account", &serde_json::json!({"Name": test_name}))
        .await
        .expect("Account creation should succeed");

    client
        .update(
            "Account",
            &account_id,
            &serde_json::json!({"Description": "Updated"}),
        )
        .await
        .expect("Update should succeed");

    tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;

    // Use a short window (5 minutes) — on new scratch orgs, the replication
    // date starts at org creation time, so "now - 1 day" is before the org existed.
    let now = chrono::Utc::now();
    let start = (now - chrono::Duration::minutes(5)).to_rfc3339();
    let end = now.to_rfc3339();

    let result = client
        .get_updated("Account", &start, &end)
        .await
        .expect("get_updated should succeed");

    assert!(!result.latest_date_covered.is_empty());

    let _ = client.delete("Account", &account_id).await;
}

// ============================================================================
// Binary Content Tests (PR #49)
// ============================================================================

#[tokio::test]
async fn test_get_blob_content() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let test_content = b"Test file content for blob retrieval";
    use base64::Engine as _;
    let base64_content = base64::engine::general_purpose::STANDARD.encode(test_content);

    let content_version_id = client
        .create(
            "ContentVersion",
            &serde_json::json!({
                "Title": format!("Test Blob {}", chrono::Utc::now().timestamp_millis()),
                "PathOnClient": "test.txt",
                "VersionData": base64_content,
            }),
        )
        .await
        .expect("ContentVersion creation should succeed");

    let query_result: Vec<serde_json::Value> = client
        .query_all(&format!(
            "SELECT ContentDocumentId FROM ContentVersion WHERE Id = '{}'",
            content_version_id
        ))
        .await
        .expect("Query should succeed");

    if let Some(cv) = query_result.first() {
        let content_document_id = cv
            .get("ContentDocumentId")
            .and_then(|v| v.as_str())
            .expect("Should have ContentDocumentId");

        let blob_data = client
            .get_blob("ContentVersion", &content_version_id, "VersionData")
            .await
            .expect("get_blob should succeed");

        assert!(!blob_data.is_empty(), "Blob data should not be empty");
        assert_eq!(
            blob_data, test_content,
            "Retrieved content should match uploaded content"
        );

        let _ = client.delete("ContentDocument", content_document_id).await;
    }
}

// ============================================================================
// Relationship Traversal Tests (PR #49)
// ============================================================================

#[tokio::test]
async fn test_get_relationship_child() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let test_name = format!(
        "Relationship Test {}",
        chrono::Utc::now().timestamp_millis()
    );
    let account_id = client
        .create("Account", &serde_json::json!({"Name": test_name}))
        .await
        .expect("Account creation should succeed");

    let contact_id = client
        .create(
            "Contact",
            &serde_json::json!({"LastName": "Test Contact", "AccountId": account_id}),
        )
        .await
        .expect("Contact creation should succeed");

    let contacts_result: busbar_sf_rest::QueryResult<serde_json::Value> = client
        .get_relationship("Account", &account_id, "Contacts")
        .await
        .expect("get_relationship should succeed");

    assert!(
        contacts_result.total_size > 0,
        "Should have at least one contact"
    );

    let _ = client.delete("Contact", &contact_id).await;
    let _ = client.delete("Account", &account_id).await;
}

#[tokio::test]
async fn test_get_relationship_parent() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let test_name = format!("Parent Test {}", chrono::Utc::now().timestamp_millis());
    let account_id = client
        .create("Account", &serde_json::json!({"Name": test_name}))
        .await
        .expect("Account creation should succeed");

    let contact_id = client
        .create(
            "Contact",
            &serde_json::json!({"LastName": "Test Contact", "AccountId": account_id}),
        )
        .await
        .expect("Contact creation should succeed");

    let account_result: serde_json::Value = client
        .get_relationship("Contact", &contact_id, "Account")
        .await
        .expect("get_relationship should succeed");

    assert!(account_result.get("Id").is_some(), "Should have account ID");

    let _ = client.delete("Contact", &contact_id).await;
    let _ = client.delete("Account", &account_id).await;
}

// ============================================================================
// SObject Basic Info Tests (PR #49)
// ============================================================================

#[tokio::test]
async fn test_get_sobject_basic_info() {
    let creds = get_credentials().await;
    let client = SalesforceRestClient::new(creds.instance_url(), creds.access_token())
        .expect("Failed to create REST client");

    let info = client
        .get_sobject_basic_info("Account")
        .await
        .expect("get_sobject_basic_info should succeed");

    assert_eq!(info.object_describe.name, "Account");
    assert!(!info.object_describe.label.is_empty());
    assert!(info.object_describe.key_prefix.is_some());
    assert!(!info.object_describe.urls.is_empty());
    assert!(info.object_describe.createable);
    assert!(info.object_describe.queryable);
}