slack-rs 0.1.70

A Slack CLI tool with OAuth authentication, profile management, and API access
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
//! Auth command implementations

use crate::auth::cloudflared::{CloudflaredError, CloudflaredTunnel};
use crate::debug;
use crate::oauth::{
    build_authorization_url, exchange_code, generate_pkce, generate_state, resolve_callback_port,
    run_callback_server, OAuthConfig, OAuthError,
};
use crate::profile::{
    create_token_store, default_config_path, load_config, make_token_key, save_config, Profile,
    ProfilesConfig,
};
use std::io::{self, Write};
use std::path::PathBuf;
use std::process::Command;

/// Configuration for login flow
struct LoginConfig {
    client_id: String,
    client_secret: String,
    redirect_uri: String,
    bot_scopes: Vec<String>,
    user_scopes: Vec<String>,
}

/// Resolve client ID from CLI args, profile, or prompt
fn resolve_client_id(
    cli_arg: Option<String>,
    existing_profile: Option<&Profile>,
    non_interactive: bool,
) -> Result<String, OAuthError> {
    if let Some(id) = cli_arg {
        return Ok(id);
    }

    if let Some(profile) = existing_profile {
        if let Some(saved_id) = &profile.client_id {
            return Ok(saved_id.clone());
        }
    }

    prompt_for_client_id_with_mode(non_interactive)
}

/// Resolve redirect URI from profile, default, or prompt
fn resolve_redirect_uri(
    existing_profile: Option<&Profile>,
    default_uri: &str,
    non_interactive: bool,
) -> Result<String, OAuthError> {
    if let Some(profile) = existing_profile {
        if let Some(saved_uri) = &profile.redirect_uri {
            return Ok(saved_uri.clone());
        }
    }

    if non_interactive {
        Ok(default_uri.to_string())
    } else {
        prompt_for_redirect_uri(default_uri)
    }
}

/// Resolve bot scopes from CLI args, profile, or prompt
fn resolve_bot_scopes(
    cli_arg: Option<Vec<String>>,
    existing_profile: Option<&Profile>,
) -> Result<Vec<String>, OAuthError> {
    if let Some(scopes) = cli_arg {
        return Ok(scopes);
    }

    if let Some(profile) = existing_profile {
        if let Some(saved_scopes) = profile.get_bot_scopes() {
            return Ok(saved_scopes);
        }
    }

    prompt_for_bot_scopes()
}

/// Resolve user scopes from CLI args, profile, or prompt
fn resolve_user_scopes(
    cli_arg: Option<Vec<String>>,
    existing_profile: Option<&Profile>,
) -> Result<Vec<String>, OAuthError> {
    if let Some(scopes) = cli_arg {
        return Ok(scopes);
    }

    if let Some(profile) = existing_profile {
        if let Some(saved_scopes) = profile.get_user_scopes() {
            return Ok(saved_scopes);
        }
    }

    prompt_for_user_scopes()
}

/// Resolve client secret from token store or prompt
fn resolve_client_secret(
    token_store: &dyn crate::profile::TokenStore,
    profile_name: &str,
    non_interactive: bool,
) -> Result<String, OAuthError> {
    match crate::profile::get_oauth_client_secret(token_store, profile_name) {
        Ok(secret) => {
            println!("Using saved client secret from token store.");
            Ok(secret)
        }
        Err(_) => {
            if non_interactive {
                Err(OAuthError::ConfigError(
                    "Client secret is required. In non-interactive mode, save it first with 'config oauth set'".to_string()
                ))
            } else {
                prompt_for_client_secret()
            }
        }
    }
}

/// Check for missing required parameters in non-interactive mode
fn check_non_interactive_params(
    client_id: &Option<String>,
    bot_scopes: &Option<Vec<String>>,
    user_scopes: &Option<Vec<String>>,
    existing_profile: Option<&Profile>,
    _profile_name: &str,
) -> Result<(), OAuthError> {
    let mut missing_params = Vec::new();

    // Check client_id
    let has_client_id = client_id.is_some()
        || existing_profile
            .and_then(|p| p.client_id.as_ref())
            .is_some();
    if !has_client_id {
        missing_params.push("--client-id <id>");
    }

    // Check bot_scopes
    let has_bot_scopes =
        bot_scopes.is_some() || existing_profile.and_then(|p| p.get_bot_scopes()).is_some();
    if !has_bot_scopes {
        missing_params.push("--bot-scopes <scopes>");
    }

    // Check user_scopes
    let has_user_scopes =
        user_scopes.is_some() || existing_profile.and_then(|p| p.get_user_scopes()).is_some();
    if !has_user_scopes {
        missing_params.push("--user-scopes <scopes>");
    }

    // If any parameters are missing, return comprehensive error
    if !missing_params.is_empty() {
        let missing_list = missing_params.join(", ");
        return Err(OAuthError::ConfigError(format!(
            "Missing required OAuth parameters in non-interactive mode: {}\n\
             Provide them via CLI flags or save with 'config oauth set':\n\
             Example: slack-rs auth login --client-id <id> --bot-scopes <scopes> --user-scopes <scopes>",
            missing_list
        )));
    }

    Ok(())
}

/// Resolve all login configuration parameters
fn resolve_login_config(
    client_id: Option<String>,
    redirect_uri: &str,
    bot_scopes: Option<Vec<String>>,
    user_scopes: Option<Vec<String>>,
    existing_profile: Option<&Profile>,
    profile_name: &str,
    non_interactive: bool,
) -> Result<LoginConfig, OAuthError> {
    let token_store = create_token_store()
        .map_err(|e| OAuthError::ConfigError(format!("Failed to create token store: {}", e)))?;

    let resolved_client_id = resolve_client_id(client_id, existing_profile, non_interactive)?;
    let resolved_redirect_uri =
        resolve_redirect_uri(existing_profile, redirect_uri, non_interactive)?;
    let resolved_bot_scopes = resolve_bot_scopes(bot_scopes, existing_profile)?;
    let resolved_user_scopes = resolve_user_scopes(user_scopes, existing_profile)?;
    let resolved_client_secret =
        resolve_client_secret(&*token_store, profile_name, non_interactive)?;

    Ok(LoginConfig {
        client_id: resolved_client_id,
        client_secret: resolved_client_secret,
        redirect_uri: resolved_redirect_uri,
        bot_scopes: resolved_bot_scopes,
        user_scopes: resolved_user_scopes,
    })
}

/// Login command with credential prompting - performs OAuth authentication
///
/// # Arguments
/// * `client_id` - Optional OAuth client ID from CLI
/// * `profile_name` - Optional profile name (defaults to "default")
/// * `redirect_uri` - OAuth redirect URI (used as fallback if not in profile)
/// * `_scopes` - OAuth scopes (legacy parameter, unused - use bot_scopes/user_scopes instead)
/// * `bot_scopes` - Optional bot scopes from CLI
/// * `user_scopes` - Optional user scopes from CLI
/// * `base_url` - Optional base URL for testing
/// * `non_interactive` - Whether running in non-interactive mode
#[allow(dead_code)]
#[allow(clippy::too_many_arguments)]
pub async fn login_with_credentials(
    client_id: Option<String>,
    profile_name: Option<String>,
    redirect_uri: String,
    _scopes: Vec<String>,
    bot_scopes: Option<Vec<String>>,
    user_scopes: Option<Vec<String>>,
    base_url: Option<String>,
    non_interactive: bool,
) -> Result<(), OAuthError> {
    let profile_name = profile_name.unwrap_or_else(|| "default".to_string());

    // Load existing config to check for saved OAuth settings
    let config_path = default_config_path()
        .map_err(|e| OAuthError::ConfigError(format!("Failed to get config path: {}", e)))?;
    let existing_config = load_config(&config_path).ok();
    let existing_profile = existing_config.as_ref().and_then(|c| c.get(&profile_name));

    // In non-interactive mode, check all required parameters first
    if non_interactive {
        check_non_interactive_params(
            &client_id,
            &bot_scopes,
            &user_scopes,
            existing_profile,
            &profile_name,
        )?;
    }

    // Resolve all login configuration parameters
    let login_config = resolve_login_config(
        client_id,
        &redirect_uri,
        bot_scopes,
        user_scopes,
        existing_profile,
        &profile_name,
        non_interactive,
    )?;

    // Create OAuth config
    let oauth_config = OAuthConfig {
        client_id: login_config.client_id.clone(),
        client_secret: login_config.client_secret.clone(),
        redirect_uri: login_config.redirect_uri.clone(),
        scopes: login_config.bot_scopes.clone(),
        user_scopes: login_config.user_scopes.clone(),
    };

    // Perform login flow (existing implementation)
    let (team_id, team_name, user_id, bot_token, user_token) =
        perform_oauth_flow(&oauth_config, base_url.as_deref()).await?;

    // Save profile with OAuth config and client_secret to Keyring
    save_profile_and_credentials(SaveCredentials {
        config_path: &config_path,
        profile_name: &profile_name,
        team_id: &team_id,
        team_name: &team_name,
        user_id: &user_id,
        bot_token: bot_token.as_deref(),
        user_token: user_token.as_deref(),
        client_id: &login_config.client_id,
        client_secret: &login_config.client_secret,
        redirect_uri: &login_config.redirect_uri,
        scopes: &login_config.bot_scopes, // Legacy field, now stores bot scopes
        bot_scopes: &login_config.bot_scopes,
        user_scopes: &login_config.user_scopes,
    })?;

    println!("✓ Authentication successful!");
    println!("Profile '{}' saved.", profile_name);

    Ok(())
}

/// Prompt user for OAuth client ID
#[allow(dead_code)]
fn prompt_for_client_id() -> Result<String, OAuthError> {
    prompt_for_client_id_with_mode(false)
}

/// Prompt user for OAuth client ID with non-interactive mode support
fn prompt_for_client_id_with_mode(non_interactive: bool) -> Result<String, OAuthError> {
    if non_interactive {
        return Err(OAuthError::ConfigError(
            "Client ID is required. In non-interactive mode, provide it via --client-id flag or save it in config with 'config oauth set'".to_string()
        ));
    }

    loop {
        print!("Enter OAuth client ID: ");
        io::stdout()
            .flush()
            .map_err(|e| OAuthError::ConfigError(format!("Failed to flush stdout: {}", e)))?;

        let mut input = String::new();
        io::stdin()
            .read_line(&mut input)
            .map_err(|e| OAuthError::ConfigError(format!("Failed to read input: {}", e)))?;

        let trimmed = input.trim();
        if !trimmed.is_empty() {
            return Ok(trimmed.to_string());
        }
        eprintln!("Client ID cannot be empty. Please try again.");
    }
}

/// Prompt user for OAuth client secret (hidden input)
fn prompt_for_client_secret() -> Result<String, OAuthError> {
    loop {
        let input = rpassword::prompt_password("Enter OAuth client secret: ")
            .map_err(|e| OAuthError::ConfigError(format!("Failed to read password: {}", e)))?;

        let trimmed = input.trim();
        if !trimmed.is_empty() {
            // Add newline after successful password input for better UX
            println!();
            return Ok(trimmed.to_string());
        }
        eprintln!("Client secret cannot be empty. Please try again.");
    }
}

/// Prompt user for OAuth redirect URI with default option
fn prompt_for_redirect_uri(default: &str) -> Result<String, OAuthError> {
    print!("Enter OAuth redirect URI [{}]: ", default);
    io::stdout()
        .flush()
        .map_err(|e| OAuthError::ConfigError(format!("Failed to flush stdout: {}", e)))?;

    let mut input = String::new();
    io::stdin()
        .read_line(&mut input)
        .map_err(|e| OAuthError::ConfigError(format!("Failed to read input: {}", e)))?;

    let trimmed = input.trim();
    if trimmed.is_empty() {
        Ok(default.to_string())
    } else {
        Ok(trimmed.to_string())
    }
}

/// Prompt user for bot OAuth scopes with default "all"
fn prompt_for_bot_scopes() -> Result<Vec<String>, OAuthError> {
    print!("Enter bot scopes (comma-separated, or 'all'/'bot:all' for preset) [all]: ");
    io::stdout()
        .flush()
        .map_err(|e| OAuthError::ConfigError(format!("Failed to flush stdout: {}", e)))?;

    let mut input = String::new();
    io::stdin()
        .read_line(&mut input)
        .map_err(|e| OAuthError::ConfigError(format!("Failed to read input: {}", e)))?;

    let trimmed = input.trim();
    let scopes_input = if trimmed.is_empty() {
        vec!["all".to_string()]
    } else {
        trimmed.split(',').map(|s| s.trim().to_string()).collect()
    };

    Ok(crate::oauth::expand_scopes_with_context(
        &scopes_input,
        true,
    ))
}

/// Prompt user for user OAuth scopes with default "all"
fn prompt_for_user_scopes() -> Result<Vec<String>, OAuthError> {
    print!("Enter user scopes (comma-separated, or 'all'/'user:all' for preset) [all]: ");
    io::stdout()
        .flush()
        .map_err(|e| OAuthError::ConfigError(format!("Failed to flush stdout: {}", e)))?;

    let mut input = String::new();
    io::stdin()
        .read_line(&mut input)
        .map_err(|e| OAuthError::ConfigError(format!("Failed to read input: {}", e)))?;

    let trimmed = input.trim();
    let scopes_input = if trimmed.is_empty() {
        vec!["all".to_string()]
    } else {
        trimmed.split(',').map(|s| s.trim().to_string()).collect()
    };

    Ok(crate::oauth::expand_scopes_with_context(
        &scopes_input,
        false,
    ))
}

/// Perform OAuth flow and return user/team info and tokens (bot and user)
async fn perform_oauth_flow(
    config: &OAuthConfig,
    base_url: Option<&str>,
) -> Result<
    (
        String,
        Option<String>,
        String,
        Option<String>,
        Option<String>,
    ),
    OAuthError,
> {
    // Validate config
    config.validate()?;

    // Generate PKCE and state
    let (code_verifier, code_challenge) = generate_pkce();
    let state = generate_state();

    // Build authorization URL
    let auth_url = build_authorization_url(config, &code_challenge, &state)?;

    println!("Opening browser for authentication...");
    println!("If the browser doesn't open, visit this URL:");
    println!("{}", auth_url);
    println!();

    // Try to open browser
    if let Err(e) = open_browser(&auth_url) {
        println!("Failed to open browser: {}", e);
        println!("Please open the URL manually in your browser.");
    }

    // Start callback server with resolved port
    let port = resolve_callback_port()?;
    println!("Waiting for authentication callback...");
    let callback_result = run_callback_server(port, state.clone(), 300).await?;

    println!("Received authorization code, exchanging for token...");

    // Exchange code for token
    let oauth_response =
        exchange_code(config, &callback_result.code, &code_verifier, base_url).await?;

    // Extract user and team information
    let team_id = oauth_response
        .team
        .as_ref()
        .map(|t| t.id.clone())
        .ok_or_else(|| OAuthError::SlackError("Missing team information".to_string()))?;

    let team_name = oauth_response.team.as_ref().map(|t| t.name.clone());

    let user_id = oauth_response
        .authed_user
        .as_ref()
        .map(|u| u.id.clone())
        .ok_or_else(|| OAuthError::SlackError("Missing user information".to_string()))?;

    // Extract bot token (from access_token field)
    let bot_token = oauth_response.access_token.clone();

    // Extract user token (from authed_user.access_token field)
    let user_token = oauth_response
        .authed_user
        .as_ref()
        .and_then(|u| u.access_token.clone());

    if debug::enabled() {
        debug::log(format!(
            "OAuth tokens received: bot_token_present={}, user_token_present={}",
            bot_token.is_some(),
            user_token.is_some()
        ));
        if let Some(ref token) = bot_token {
            debug::log(format!("bot_token={}", debug::token_hint(token)));
        }
        if let Some(ref token) = user_token {
            debug::log(format!("user_token={}", debug::token_hint(token)));
        }
    }

    // Ensure at least one token is present
    if bot_token.is_none() && user_token.is_none() {
        return Err(OAuthError::SlackError(
            "No access tokens received".to_string(),
        ));
    }

    Ok((team_id, team_name, user_id, bot_token, user_token))
}

/// Credentials to save after OAuth authentication
struct SaveCredentials<'a> {
    config_path: &'a std::path::Path,
    profile_name: &'a str,
    team_id: &'a str,
    team_name: &'a Option<String>,
    user_id: &'a str,
    bot_token: Option<&'a str>,  // Bot token (optional)
    user_token: Option<&'a str>, // User token (optional)
    client_id: &'a str,
    client_secret: &'a str,
    redirect_uri: &'a str,
    scopes: &'a [String],      // Legacy field for backward compatibility
    bot_scopes: &'a [String],  // New bot scopes field
    user_scopes: &'a [String], // New user scopes field
}

/// Save profile and credentials (including client_id and client_secret)
fn save_profile_and_credentials(creds: SaveCredentials) -> Result<(), OAuthError> {
    // Load or create config
    let mut profiles_config =
        load_config(creds.config_path).unwrap_or_else(|_| ProfilesConfig::new());

    // Get existing profile's default_token_type (if it exists)
    let existing_default_token_type = profiles_config
        .get(creds.profile_name)
        .and_then(|p| p.default_token_type);

    // Compute default token type based on available tokens
    let has_user_token = creds.user_token.is_some();
    let default_token_type =
        compute_initial_default_token_type(existing_default_token_type, has_user_token);

    // Create profile with OAuth config (client_id, redirect_uri, bot_scopes, user_scopes)
    let profile = Profile {
        team_id: creds.team_id.to_string(),
        user_id: creds.user_id.to_string(),
        team_name: creds.team_name.clone(),
        user_name: None,
        client_id: Some(creds.client_id.to_string()),
        redirect_uri: Some(creds.redirect_uri.to_string()),
        scopes: Some(creds.scopes.to_vec()), // Legacy field
        bot_scopes: Some(creds.bot_scopes.to_vec()),
        user_scopes: Some(creds.user_scopes.to_vec()),
        default_token_type: Some(default_token_type),
    };

    profiles_config
        .set_or_update(creds.profile_name.to_string(), profile)
        .map_err(|e| OAuthError::ConfigError(format!("Failed to save profile: {}", e)))?;

    save_config(creds.config_path, &profiles_config)
        .map_err(|e| OAuthError::ConfigError(format!("Failed to save config: {}", e)))?;

    // Save tokens to token store
    let token_store = create_token_store()
        .map_err(|e| OAuthError::ConfigError(format!("Failed to create token store: {}", e)))?;

    // Save bot token to team_id:user_id key (make_token_key format)
    if let Some(bot_token) = creds.bot_token {
        let bot_token_key = make_token_key(creds.team_id, creds.user_id);
        token_store
            .set(&bot_token_key, bot_token)
            .map_err(|e| OAuthError::ConfigError(format!("Failed to save bot token: {}", e)))?;
    }

    // Save user token to separate key (team_id:user_id:user)
    if let Some(user_token) = creds.user_token {
        let user_token_key = format!("{}:{}:user", creds.team_id, creds.user_id);
        debug::log(format!("Saving user token with key: {}", user_token_key));
        token_store
            .set(&user_token_key, user_token)
            .map_err(|e| OAuthError::ConfigError(format!("Failed to save user token: {}", e)))?;
        debug::log("User token saved successfully");
    } else {
        debug::log("No user token to save (user_token is None)");
    }

    // Save client_secret to token store
    let client_secret_key = format!("oauth-client-secret:{}", creds.profile_name);
    token_store
        .set(&client_secret_key, creds.client_secret)
        .map_err(|e| OAuthError::ConfigError(format!("Failed to save client secret: {}", e)))?;

    Ok(())
}

/// Login command - performs OAuth authentication (legacy, delegates to login_with_credentials)
///
/// # Arguments
/// * `config` - OAuth configuration
/// * `profile_name` - Optional profile name (defaults to "default")
/// * `base_url` - Optional base URL for testing
#[allow(dead_code)]
pub async fn login(
    config: OAuthConfig,
    profile_name: Option<String>,
    base_url: Option<String>,
) -> Result<(), OAuthError> {
    // Validate config
    config.validate()?;

    let profile_name = profile_name.unwrap_or_else(|| "default".to_string());

    // Generate PKCE and state
    let (code_verifier, code_challenge) = generate_pkce();
    let state = generate_state();

    // Build authorization URL
    let auth_url = build_authorization_url(&config, &code_challenge, &state)?;

    println!("Opening browser for authentication...");
    println!("If the browser doesn't open, visit this URL:");
    println!("{}", auth_url);
    println!();

    // Try to open browser
    if let Err(e) = open_browser(&auth_url) {
        println!("Failed to open browser: {}", e);
        println!("Please open the URL manually in your browser.");
    }

    // Start callback server with resolved port
    let port = resolve_callback_port()?;
    println!("Waiting for authentication callback...");
    let callback_result = run_callback_server(port, state.clone(), 300).await?;

    println!("Received authorization code, exchanging for token...");

    // Exchange code for token
    let oauth_response = exchange_code(
        &config,
        &callback_result.code,
        &code_verifier,
        base_url.as_deref(),
    )
    .await?;

    // Extract user and team information
    let team_id = oauth_response
        .team
        .as_ref()
        .map(|t| t.id.clone())
        .ok_or_else(|| OAuthError::SlackError("Missing team information".to_string()))?;

    let team_name = oauth_response.team.as_ref().map(|t| t.name.clone());

    let user_id = oauth_response
        .authed_user
        .as_ref()
        .map(|u| u.id.clone())
        .ok_or_else(|| OAuthError::SlackError("Missing user information".to_string()))?;

    let token = oauth_response
        .authed_user
        .as_ref()
        .and_then(|u| u.access_token.clone())
        .or(oauth_response.access_token.clone())
        .ok_or_else(|| OAuthError::SlackError("Missing access token".to_string()))?;

    // Save profile
    let config_path = default_config_path()
        .map_err(|e| OAuthError::ConfigError(format!("Failed to get config path: {}", e)))?;

    let mut config = load_config(&config_path).unwrap_or_else(|_| ProfilesConfig::new());

    let profile = Profile {
        team_id: team_id.clone(),
        user_id: user_id.clone(),
        team_name,
        user_name: None, // We don't get user name from OAuth response
        client_id: None, // OAuth client ID not stored in legacy login flow
        redirect_uri: None,
        scopes: None,
        bot_scopes: None,
        user_scopes: None,
        default_token_type: None,
    };

    config
        .set_or_update(profile_name.clone(), profile)
        .map_err(|e| OAuthError::ConfigError(format!("Failed to save profile: {}", e)))?;

    save_config(&config_path, &config)
        .map_err(|e| OAuthError::ConfigError(format!("Failed to save config: {}", e)))?;

    // Save token
    let token_store = create_token_store()
        .map_err(|e| OAuthError::ConfigError(format!("Failed to create token store: {}", e)))?;
    let token_key = make_token_key(&team_id, &user_id);
    token_store
        .set(&token_key, &token)
        .map_err(|e| OAuthError::ConfigError(format!("Failed to save token: {}", e)))?;

    println!("✓ Authentication successful!");
    println!("Profile '{}' saved.", profile_name);

    Ok(())
}

/// Status command - shows current profile status
///
/// # Arguments
/// * `profile_name` - Optional profile name (defaults to "default")
pub fn status(profile_name: Option<String>) -> Result<(), String> {
    let profile_name = profile_name.unwrap_or_else(|| "default".to_string());

    let config_path = default_config_path().map_err(|e| e.to_string())?;
    let config = load_config(&config_path).map_err(|e| e.to_string())?;

    let profile = config
        .get(&profile_name)
        .ok_or_else(|| format!("Profile '{}' not found", profile_name))?;

    println!("Profile: {}", profile_name);
    println!("Team ID: {}", profile.team_id);
    println!("User ID: {}", profile.user_id);
    if let Some(team_name) = &profile.team_name {
        println!("Team Name: {}", team_name);
    }
    if let Some(user_name) = &profile.user_name {
        println!("User Name: {}", user_name);
    }
    if let Some(client_id) = &profile.client_id {
        println!("Client ID: {}", client_id);
    }

    // Display SLACK_TOKEN environment variable status (without showing value)
    if std::env::var("SLACK_TOKEN").is_ok() {
        println!("SLACK_TOKEN: set");
    }

    // Display token store backend and storage location
    use crate::profile::FileTokenStore;
    let file_path = FileTokenStore::default_path().map_err(|e| e.to_string())?;
    println!("Token Store: file ({})", file_path.display());

    // Check if tokens exist
    let token_store = create_token_store().map_err(|e| e.to_string())?;
    let bot_token_key = make_token_key(&profile.team_id, &profile.user_id);
    let user_token_key = format!("{}:{}:user", &profile.team_id, &profile.user_id);

    let has_bot_token = token_store.exists(&bot_token_key);
    let has_user_token = token_store.exists(&user_token_key);

    // Display available tokens
    let mut available_tokens = Vec::new();
    if has_bot_token {
        available_tokens.push("Bot");
    }
    if has_user_token {
        available_tokens.push("User");
    }

    if available_tokens.is_empty() {
        println!("Tokens Available: None");
    } else {
        println!("Tokens Available: {}", available_tokens.join(", "));
    }

    // Display Bot ID if bot token exists
    if has_bot_token {
        // Extract Bot ID from bot token if available
        if let Ok(bot_token) = token_store.get(&bot_token_key) {
            if let Some(bot_id) = extract_bot_id(&bot_token) {
                println!("Bot ID: {}", bot_id);
            }
        }
    }

    // Display scopes
    if let Some(bot_scopes) = profile.get_bot_scopes() {
        if !bot_scopes.is_empty() {
            println!("Bot Scopes: {}", bot_scopes.join(", "));
        }
    }
    if let Some(user_scopes) = profile.get_user_scopes() {
        if !user_scopes.is_empty() {
            println!("User Scopes: {}", user_scopes.join(", "));
        }
    }

    // Display default token type using pure function
    let default_token_type =
        compute_default_token_type_display(profile.default_token_type, has_user_token);
    println!("Default Token Type: {}", default_token_type);

    Ok(())
}

/// Compute default token type for display in `auth status`
///
/// Priority: 1. profile.default_token_type (if set)
///           2. Infer from available tokens (user if available, else bot)
///
/// # Arguments
/// * `profile_default_token_type` - Default token type stored in profile
/// * `has_user_token` - Whether user token exists in token store
///
/// # Returns
/// Static string for display: "Bot" or "User"
fn compute_default_token_type_display(
    profile_default_token_type: Option<crate::profile::TokenType>,
    has_user_token: bool,
) -> &'static str {
    if let Some(token_type) = profile_default_token_type {
        match token_type {
            crate::profile::TokenType::Bot => "Bot",
            crate::profile::TokenType::User => "User",
        }
    } else if has_user_token {
        "User"
    } else {
        "Bot"
    }
}

/// Compute initial default token type during login
///
/// This function determines the default token type to save in the profile during login.
/// It only computes the value when `existing_default_token_type` is None.
/// If a default token type is already set, it is preserved.
///
/// # Arguments
/// * `existing_default_token_type` - Default token type already stored in profile (if any)
/// * `has_user_token` - Whether user token was obtained during OAuth flow
///
/// # Returns
/// The default token type to store in the profile:
/// - Returns existing value if already set
/// - Returns User if user token is available
/// - Returns Bot if user token is not available
///
/// # Examples
/// ```
/// use slack_rs::profile::TokenType;
/// use slack_rs::auth::commands::compute_initial_default_token_type;
///
/// // New profile with user token -> User
/// assert_eq!(
///     compute_initial_default_token_type(None, true),
///     TokenType::User
/// );
///
/// // New profile without user token -> Bot
/// assert_eq!(
///     compute_initial_default_token_type(None, false),
///     TokenType::Bot
/// );
///
/// // Existing profile with Bot default -> preserve Bot
/// assert_eq!(
///     compute_initial_default_token_type(Some(TokenType::Bot), true),
///     TokenType::Bot
/// );
///
/// // Existing profile with User default -> preserve User
/// assert_eq!(
///     compute_initial_default_token_type(Some(TokenType::User), false),
///     TokenType::User
/// );
/// ```
pub fn compute_initial_default_token_type(
    existing_default_token_type: Option<crate::profile::TokenType>,
    has_user_token: bool,
) -> crate::profile::TokenType {
    // Preserve existing setting if present
    if let Some(token_type) = existing_default_token_type {
        return token_type;
    }

    // For new profiles, infer from available tokens
    if has_user_token {
        crate::profile::TokenType::User
    } else {
        crate::profile::TokenType::Bot
    }
}

/// Extract Bot ID from a bot token
/// Bot tokens have format xoxb-{team_id}-{bot_id}-{secret}
fn extract_bot_id(token: &str) -> Option<String> {
    if token.starts_with("xoxb-") {
        let parts: Vec<&str> = token.split('-').collect();
        // xoxb-{team_id}-{bot_id}-{secret}
        // parts[0] = "xoxb", parts[1] = team_id, parts[2] = bot_id
        if parts.len() >= 3 {
            return Some(parts[2].to_string());
        }
    }
    None
}

/// List command - lists all profiles
pub fn list() -> Result<(), String> {
    let config_path = default_config_path().map_err(|e| e.to_string())?;
    let config = load_config(&config_path).map_err(|e| e.to_string())?;

    if config.profiles.is_empty() {
        println!("No profiles found.");
        return Ok(());
    }

    println!("Profiles:");
    for name in config.list_names() {
        if let Some(profile) = config.get(&name) {
            let team_name = profile.team_name.as_deref().unwrap_or(&profile.team_id);
            println!(
                "  {}: {} ({}:{})",
                name, team_name, profile.team_id, profile.user_id
            );
        }
    }

    Ok(())
}

/// Rename command - renames a profile
///
/// # Arguments
/// * `old_name` - Current profile name
/// * `new_name` - New profile name
pub fn rename(old_name: String, new_name: String) -> Result<(), String> {
    let config_path = default_config_path().map_err(|e| e.to_string())?;
    let mut config = load_config(&config_path).map_err(|e| e.to_string())?;

    // Check if old profile exists
    let profile = config
        .get(&old_name)
        .ok_or_else(|| format!("Profile '{}' not found", old_name))?
        .clone();

    // Check if new name already exists
    if config.get(&new_name).is_some() {
        return Err(format!("Profile '{}' already exists", new_name));
    }

    // Remove old profile and add with new name
    config.remove(&old_name);
    config.set(new_name.clone(), profile);

    save_config(&config_path, &config).map_err(|e| e.to_string())?;

    println!("Profile '{}' renamed to '{}'", old_name, new_name);

    Ok(())
}

/// Logout command - removes authentication
///
/// # Arguments
/// * `profile_name` - Optional profile name (defaults to "default")
pub fn logout(profile_name: Option<String>) -> Result<(), String> {
    let profile_name = profile_name.unwrap_or_else(|| "default".to_string());

    let config_path = default_config_path().map_err(|e| e.to_string())?;
    let mut config = load_config(&config_path).map_err(|e| e.to_string())?;

    let profile = config
        .get(&profile_name)
        .ok_or_else(|| format!("Profile '{}' not found", profile_name))?
        .clone();

    // Delete token
    let token_store = create_token_store().map_err(|e| e.to_string())?;
    let token_key = make_token_key(&profile.team_id, &profile.user_id);
    let _ = token_store.delete(&token_key); // Ignore error if token doesn't exist

    // Remove profile
    config.remove(&profile_name);
    save_config(&config_path, &config).map_err(|e| e.to_string())?;

    println!("Profile '{}' removed", profile_name);

    Ok(())
}

/// Try to open a URL in the default browser
fn open_browser(url: &str) -> Result<(), String> {
    #[cfg(target_os = "macos")]
    let result = Command::new("open").arg(url).spawn();

    #[cfg(target_os = "linux")]
    let result = Command::new("xdg-open").arg(url).spawn();

    #[cfg(target_os = "windows")]
    let result = Command::new("cmd").args(["/C", "start", url]).spawn();

    #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
    let result: Result<std::process::Child, std::io::Error> = Err(std::io::Error::new(
        std::io::ErrorKind::Unsupported,
        "Unsupported platform",
    ));

    result.map(|_| ()).map_err(|e| e.to_string())
}

/// Find cloudflared executable in PATH or common locations
fn find_cloudflared() -> Option<String> {
    // Try "cloudflared" in PATH first
    if Command::new("cloudflared")
        .arg("--version")
        .output()
        .is_ok()
    {
        return Some("cloudflared".to_string());
    }

    // Try common installation paths
    let common_paths = [
        "/usr/local/bin/cloudflared",
        "/opt/homebrew/bin/cloudflared",
        "/usr/bin/cloudflared",
    ];

    for path in &common_paths {
        if std::path::Path::new(path).exists() {
            return Some(path.to_string());
        }
    }

    None
}

/// Generate and save manifest file for Slack app creation
fn generate_and_save_manifest(
    redirect_uri: &str,
    bot_scopes: &[String],
    user_scopes: &[String],
    profile_name: &str,
) -> Result<PathBuf, OAuthError> {
    use crate::auth::manifest::generate_manifest;
    use std::fs;

    // Generate manifest YAML (no client_id needed - manifest uses only redirect URI, scopes, and profile)
    let manifest_yaml = generate_manifest(bot_scopes, user_scopes, redirect_uri, profile_name)
        .map_err(|e| OAuthError::ConfigError(format!("Failed to generate manifest: {}", e)))?;

    // Determine save path using unified config directory
    // Use directories::BaseDirs for cross-platform home directory detection
    let home = directories::BaseDirs::new()
        .ok_or_else(|| OAuthError::ConfigError("Failed to determine home directory".to_string()))?
        .home_dir()
        .to_path_buf();

    // Use separate join calls to ensure consistent path separators on Windows
    let config_dir = home.join(".config").join("slack-rs");

    // Create directory if it doesn't exist
    fs::create_dir_all(&config_dir).map_err(|e| {
        OAuthError::ConfigError(format!("Failed to create config directory: {}", e))
    })?;

    let manifest_path = config_dir.join(format!("{}_manifest.yml", profile_name));

    // Write manifest to file
    fs::write(&manifest_path, &manifest_yaml)
        .map_err(|e| OAuthError::ConfigError(format!("Failed to write manifest file: {}", e)))?;

    // Try to copy manifest to clipboard with fallback strategies
    use crate::auth::clipboard::{copy_to_clipboard, ClipboardResult};

    match copy_to_clipboard(&manifest_yaml) {
        ClipboardResult::Success(method) => {
            println!("✓ Manifest copied to clipboard ({})!", method);
        }
        ClipboardResult::Failed => {
            eprintln!("⚠️  Warning: Could not copy to clipboard.");
            eprintln!("   Please manually copy from: {}", manifest_path.display());
        }
    }

    Ok(manifest_path)
}

/// Extended login options
#[allow(dead_code)]
pub struct ExtendedLoginOptions {
    pub client_id: Option<String>,
    pub profile_name: Option<String>,
    pub redirect_uri: String,
    pub bot_scopes: Option<Vec<String>>,
    pub user_scopes: Option<Vec<String>>,
    pub cloudflared_path: Option<String>,
    pub ngrok_path: Option<String>,
    pub base_url: Option<String>,
}

/// Extended login with cloudflared/ngrok tunnel support (manifest-first flow)
///
/// This function handles OAuth flow with tunnel support for public redirect URIs.
/// The flow is manifest-first: tunnel is started, manifest is generated and shown
/// to the user, and only after the user creates the Slack App are credentials
/// (Client ID / Client Secret) collected.
pub async fn login_with_credentials_extended(
    bot_scopes: Vec<String>,
    user_scopes: Vec<String>,
    profile_name: Option<String>,
    use_cloudflared: bool,
) -> Result<(), OAuthError> {
    let profile_name = profile_name.unwrap_or_else(|| "default".to_string());

    if debug::enabled() {
        debug::log(format!(
            "login_with_credentials_extended: profile={}, bot_scopes_count={}, user_scopes_count={}",
            profile_name,
            bot_scopes.len(),
            user_scopes.len()
        ));
    }

    // Resolve port early
    let port = resolve_callback_port()?;

    let final_redirect_uri: String;
    let mut cloudflared_tunnel: Option<CloudflaredTunnel> = None;

    if use_cloudflared {
        // Check if cloudflared is installed
        let path = match find_cloudflared() {
            Some(p) => p,
            None => {
                return Err(OAuthError::ConfigError(
                    "cloudflared not found. Please install it first:\n  \
                     macOS: brew install cloudflare/cloudflare/cloudflared\n  \
                     Linux: See https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/installation/"
                        .to_string(),
                ));
            }
        };

        println!("Starting cloudflared tunnel...");
        let local_url = format!("http://localhost:{}", port);
        match CloudflaredTunnel::start(&path, &local_url, 30) {
            Ok(mut t) => {
                let public_url = t.public_url().to_string();
                println!("✓ Tunnel started: {}", public_url);
                println!("  Tunneling {} -> {}", public_url, local_url);

                if !t.is_running() {
                    return Err(OAuthError::ConfigError(
                        "Cloudflared tunnel started but process is not running".to_string(),
                    ));
                }

                final_redirect_uri = format!("{}/callback", public_url);
                println!("Using redirect URI: {}", final_redirect_uri);
                cloudflared_tunnel = Some(t);
            }
            Err(CloudflaredError::StartError(msg)) => {
                return Err(OAuthError::ConfigError(format!(
                    "Failed to start cloudflared: {}",
                    msg
                )));
            }
            Err(CloudflaredError::UrlExtractionError(msg)) => {
                return Err(OAuthError::ConfigError(format!(
                    "Failed to extract cloudflared URL: {}",
                    msg
                )));
            }
            Err(e) => {
                return Err(OAuthError::ConfigError(format!(
                    "Cloudflared error: {:?}",
                    e
                )));
            }
        }
    } else {
        final_redirect_uri = format!("http://localhost:{}/callback", port);
    }

    // Generate and save manifest BEFORE collecting credentials
    let manifest_path = generate_and_save_manifest(
        &final_redirect_uri,
        &bot_scopes,
        &user_scopes,
        &profile_name,
    )?;

    println!("\n📋 Slack App Manifest saved to:");
    println!("   {}", manifest_path.display());
    println!("\n🔧 Setup Instructions:");
    println!("   1. Go to https://api.slack.com/apps");
    println!("   2. Click 'Create New App' → 'From an app manifest'");
    println!("   3. Select your workspace");
    println!("   4. Copy and paste the manifest from the file above");
    println!("   5. Click 'Create'");
    println!("   6. Go to 'Basic Information' → 'App Credentials'");
    println!("      You will need the Client ID and Client Secret below.");
    println!("\n⏸️  Press Enter when you've created the app...");

    let mut input = String::new();
    std::io::stdin()
        .read_line(&mut input)
        .map_err(|e| OAuthError::ConfigError(format!("Failed to read input: {}", e)))?;

    // Verify tunnel is still running
    if let Some(ref mut tunnel) = cloudflared_tunnel {
        if !tunnel.is_running() {
            return Err(OAuthError::ConfigError(
                "Cloudflared tunnel stopped unexpectedly".to_string(),
            ));
        }
        println!("✓ Tunnel is running");
    }

    // NOW collect credentials (after app creation)
    // Try to reuse saved credentials from token store, otherwise prompt
    let token_store = create_token_store()
        .map_err(|e| OAuthError::ConfigError(format!("Failed to create token store: {}", e)))?;

    println!("\n🔑 Enter credentials from 'Basic Information' → 'App Credentials':");

    let client_id = {
        // Check for saved client_id in existing profile
        let config_path = default_config_path()
            .map_err(|e| OAuthError::ConfigError(format!("Failed to get config path: {}", e)))?;
        let existing_config = load_config(&config_path).ok();
        let existing_profile = existing_config.as_ref().and_then(|c| c.get(&profile_name));

        if let Some(saved_id) = existing_profile.and_then(|p| p.client_id.as_ref()) {
            println!("Using saved Client ID: {}", saved_id);
            saved_id.clone()
        } else {
            print!("Enter Slack Client ID: ");
            io::stdout()
                .flush()
                .map_err(|e| OAuthError::ConfigError(format!("Failed to flush stdout: {}", e)))?;
            let mut id_input = String::new();
            io::stdin()
                .read_line(&mut id_input)
                .map_err(|e| OAuthError::ConfigError(format!("Failed to read input: {}", e)))?;
            id_input.trim().to_string()
        }
    };

    let client_secret = resolve_client_secret(&*token_store, &profile_name, false)?;

    // Build OAuth config
    let config = OAuthConfig {
        client_id: client_id.clone(),
        client_secret: client_secret.clone(),
        redirect_uri: final_redirect_uri.clone(),
        scopes: bot_scopes.clone(),
        user_scopes: user_scopes.clone(),
    };

    // Perform OAuth flow (handles browser opening, callback server, token exchange)
    println!("\n🔄 Starting OAuth flow...");
    println!("⚠️  IMPORTANT: Do NOT click 'Install to Workspace' manually!");
    println!("   The OAuth flow will handle installation automatically.\n");
    let (team_id, team_name, user_id, bot_token, user_token) =
        perform_oauth_flow(&config, None).await?;

    if debug::enabled() {
        debug::log(format!(
            "OAuth flow completed: team_id={}, user_id={}, team_name={:?}",
            team_id, user_id, team_name
        ));
        debug::log(format!(
            "tokens: bot_token_present={}, user_token_present={}",
            bot_token.is_some(),
            user_token.is_some()
        ));
        if let Some(ref token) = bot_token {
            debug::log(format!("bot_token={}", debug::token_hint(token)));
        }
        if let Some(ref token) = user_token {
            debug::log(format!("user_token={}", debug::token_hint(token)));
        }
    }

    // Save profile
    println!("💾 Saving profile and credentials...");
    save_profile_and_credentials(SaveCredentials {
        config_path: &default_config_path()
            .map_err(|e| OAuthError::ConfigError(format!("Failed to get config path: {}", e)))?,
        profile_name: &profile_name,
        team_id: &team_id,
        team_name: &team_name,
        user_id: &user_id,
        bot_token: bot_token.as_deref(),
        user_token: user_token.as_deref(),
        client_id: &client_id,
        client_secret: &client_secret,
        redirect_uri: &final_redirect_uri,
        scopes: &bot_scopes,
        bot_scopes: &bot_scopes,
        user_scopes: &user_scopes,
    })?;

    println!("\n✅ Login successful!");
    println!("Profile '{}' has been saved.", profile_name);

    // Cleanup
    drop(cloudflared_tunnel);

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::profile::TokenStore;

    #[test]
    fn test_status_profile_not_found() {
        let result = status(Some("nonexistent".to_string()));
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("not found"));
    }

    #[test]
    fn test_extract_bot_id_valid() {
        // Test valid bot token format
        let token = "xoxb-T123-B456-secret123";
        assert_eq!(extract_bot_id(token), Some("B456".to_string()));
    }

    #[test]
    fn test_extract_bot_id_invalid() {
        // Test invalid formats
        assert_eq!(extract_bot_id("xoxp-user-token"), None);
        assert_eq!(extract_bot_id("xoxb-only"), None);
        assert_eq!(extract_bot_id("xoxb-T123"), None);
        assert_eq!(extract_bot_id("not-a-token"), None);
        assert_eq!(extract_bot_id(""), None);
    }

    #[test]
    fn test_extract_bot_id_edge_cases() {
        // Test various bot token formats
        assert_eq!(
            extract_bot_id("xoxb-123456-789012-abcdef"),
            Some("789012".to_string())
        );
        assert_eq!(
            extract_bot_id("xoxb-T123-B456-secret123"),
            Some("B456".to_string())
        );

        // Test with extra dashes in secret (should still work)
        assert_eq!(
            extract_bot_id("xoxb-T123-B456-secret-with-dashes"),
            Some("B456".to_string())
        );
    }

    #[test]
    fn test_list_empty() {
        // This test may fail if there are existing profiles
        // It's more of a demonstration of how to use the function
        let result = list();
        assert!(result.is_ok());
    }

    #[test]
    fn test_rename_nonexistent_profile() {
        let result = rename("nonexistent".to_string(), "new_name".to_string());
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("not found"));
    }

    #[test]
    fn test_logout_nonexistent_profile() {
        let result = logout(Some("nonexistent".to_string()));
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("not found"));
    }

    #[test]
    #[serial_test::serial]
    fn test_save_profile_and_credentials_with_client_id() {
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("profiles.json");

        let team_id = "T123";
        let user_id = "U456";
        let profile_name = "test";

        // Use a temporary token store file with file backend
        let tokens_path = temp_dir.path().join("tokens.json");
        std::env::set_var("SLACK_RS_TOKENS_PATH", tokens_path.to_str().unwrap());

        // Save profile with client_id and client_secret to file store
        let scopes = vec!["chat:write".to_string(), "users:read".to_string()];
        let bot_scopes = vec!["chat:write".to_string()];
        let user_scopes = vec!["users:read".to_string()];
        save_profile_and_credentials(SaveCredentials {
            config_path: &config_path,
            profile_name,
            team_id,
            team_name: &Some("Test Team".to_string()),
            user_id,
            bot_token: Some("xoxb-test-bot-token"),
            user_token: Some("xoxp-test-user-token"),
            client_id: "test-client-id",
            client_secret: "test-client-secret",
            redirect_uri: "http://127.0.0.1:8765/callback",
            scopes: &scopes,
            bot_scopes: &bot_scopes,
            user_scopes: &user_scopes,
        })
        .unwrap();

        // Verify profile was saved with client_id
        let config = load_config(&config_path).unwrap();
        let profile = config.get(profile_name).unwrap();
        assert_eq!(profile.client_id, Some("test-client-id".to_string()));
        assert_eq!(profile.team_id, team_id);
        assert_eq!(profile.user_id, user_id);

        // Verify tokens were saved to token store (file mode for this test)
        use crate::profile::FileTokenStore;
        let token_store = FileTokenStore::with_path(tokens_path.clone()).unwrap();
        let bot_token_key = make_token_key(team_id, user_id);
        let user_token_key = format!("{}:{}:user", team_id, user_id);
        let client_secret_key = format!("oauth-client-secret:{}", profile_name);

        assert!(token_store.exists(&bot_token_key));
        assert!(token_store.exists(&user_token_key));
        assert!(token_store.exists(&client_secret_key));

        // Clean up environment variables
        std::env::remove_var("SLACK_RS_TOKENS_PATH");
    }

    #[test]
    #[serial_test::serial]
    fn test_save_profile_and_credentials_sets_default_token_type_user() {
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("profiles.json");
        let tokens_path = temp_dir.path().join("tokens.json");
        std::env::set_var("SLACK_RS_TOKENS_PATH", tokens_path.to_str().unwrap());

        let team_id = "T123";
        let user_id = "U456";
        let profile_name = "test";

        // Save profile with both bot and user tokens
        let scopes = vec!["chat:write".to_string()];
        let bot_scopes = vec!["chat:write".to_string()];
        let user_scopes = vec!["users:read".to_string()];
        save_profile_and_credentials(SaveCredentials {
            config_path: &config_path,
            profile_name,
            team_id,
            team_name: &Some("Test Team".to_string()),
            user_id,
            bot_token: Some("xoxb-test-bot-token"),
            user_token: Some("xoxp-test-user-token"), // User token present
            client_id: "test-client-id",
            client_secret: "test-client-secret",
            redirect_uri: "http://127.0.0.1:8765/callback",
            scopes: &scopes,
            bot_scopes: &bot_scopes,
            user_scopes: &user_scopes,
        })
        .unwrap();

        // Verify default_token_type is set to User
        let config = load_config(&config_path).unwrap();
        let profile = config.get(profile_name).unwrap();
        assert_eq!(
            profile.default_token_type,
            Some(crate::profile::TokenType::User)
        );

        std::env::remove_var("SLACK_RS_TOKENS_PATH");
    }

    #[test]
    #[serial_test::serial]
    fn test_save_profile_and_credentials_sets_default_token_type_bot() {
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("profiles.json");
        let tokens_path = temp_dir.path().join("tokens.json");
        std::env::set_var("SLACK_RS_TOKENS_PATH", tokens_path.to_str().unwrap());

        let team_id = "T123";
        let user_id = "U456";
        let profile_name = "test";

        // Save profile with only bot token (no user token)
        let scopes = vec!["chat:write".to_string()];
        let bot_scopes = vec!["chat:write".to_string()];
        let user_scopes = vec!["users:read".to_string()];
        save_profile_and_credentials(SaveCredentials {
            config_path: &config_path,
            profile_name,
            team_id,
            team_name: &Some("Test Team".to_string()),
            user_id,
            bot_token: Some("xoxb-test-bot-token"),
            user_token: None, // No user token
            client_id: "test-client-id",
            client_secret: "test-client-secret",
            redirect_uri: "http://127.0.0.1:8765/callback",
            scopes: &scopes,
            bot_scopes: &bot_scopes,
            user_scopes: &user_scopes,
        })
        .unwrap();

        // Verify default_token_type is set to Bot
        let config = load_config(&config_path).unwrap();
        let profile = config.get(profile_name).unwrap();
        assert_eq!(
            profile.default_token_type,
            Some(crate::profile::TokenType::Bot)
        );

        std::env::remove_var("SLACK_RS_TOKENS_PATH");
    }

    #[test]
    #[serial_test::serial]
    fn test_save_profile_and_credentials_preserves_existing_default_token_type() {
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("profiles.json");
        let tokens_path = temp_dir.path().join("tokens.json");
        std::env::set_var("SLACK_RS_TOKENS_PATH", tokens_path.to_str().unwrap());

        let team_id = "T123";
        let user_id = "U456";
        let profile_name = "test";

        // First, create a profile with default_token_type=Bot
        let mut config = ProfilesConfig::new();
        config.set(
            profile_name.to_string(),
            Profile {
                team_id: team_id.to_string(),
                user_id: user_id.to_string(),
                team_name: Some("Test Team".to_string()),
                user_name: None,
                client_id: Some("test-client-id".to_string()),
                redirect_uri: Some("http://127.0.0.1:8765/callback".to_string()),
                scopes: Some(vec!["chat:write".to_string()]),
                bot_scopes: Some(vec!["chat:write".to_string()]),
                user_scopes: Some(vec!["users:read".to_string()]),
                default_token_type: Some(crate::profile::TokenType::Bot),
            },
        );
        save_config(&config_path, &config).unwrap();

        // Now "re-login" with user token available
        let scopes = vec!["chat:write".to_string()];
        let bot_scopes = vec!["chat:write".to_string()];
        let user_scopes = vec!["users:read".to_string()];
        save_profile_and_credentials(SaveCredentials {
            config_path: &config_path,
            profile_name,
            team_id,
            team_name: &Some("Test Team".to_string()),
            user_id,
            bot_token: Some("xoxb-test-bot-token"),
            user_token: Some("xoxp-test-user-token"), // User token now available
            client_id: "test-client-id",
            client_secret: "test-client-secret",
            redirect_uri: "http://127.0.0.1:8765/callback",
            scopes: &scopes,
            bot_scopes: &bot_scopes,
            user_scopes: &user_scopes,
        })
        .unwrap();

        // Verify default_token_type is preserved as Bot (not changed to User)
        let config = load_config(&config_path).unwrap();
        let profile = config.get(profile_name).unwrap();
        assert_eq!(
            profile.default_token_type,
            Some(crate::profile::TokenType::Bot),
            "Existing default_token_type should be preserved"
        );

        std::env::remove_var("SLACK_RS_TOKENS_PATH");
    }

    #[test]
    fn test_backward_compatibility_load_profile_without_client_id() {
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("profiles.json");

        // Create old-format profile without client_id
        let mut config = ProfilesConfig::new();
        config.set(
            "legacy".to_string(),
            Profile {
                team_id: "T999".to_string(),
                user_id: "U888".to_string(),
                team_name: Some("Legacy Team".to_string()),
                user_name: Some("Legacy User".to_string()),
                client_id: None,
                redirect_uri: None,
                scopes: None,
                bot_scopes: None,
                user_scopes: None,
                default_token_type: None,
            },
        );
        save_config(&config_path, &config).unwrap();

        // Verify it can be loaded
        let loaded_config = load_config(&config_path).unwrap();
        let profile = loaded_config.get("legacy").unwrap();
        assert_eq!(profile.client_id, None);
        assert_eq!(profile.team_id, "T999");
    }

    #[test]
    fn test_bot_and_user_token_storage_keys() {
        use crate::profile::InMemoryTokenStore;

        // Create token store
        let token_store = InMemoryTokenStore::new();

        // Test credentials
        let team_id = "T123";
        let user_id = "U456";
        let bot_token = "xoxb-test-bot-token";
        let user_token = "xoxp-test-user-token";

        // Simulate what save_profile_and_credentials does
        let bot_token_key = make_token_key(team_id, user_id); // team_id:user_id
        let user_token_key = format!("{}:{}:user", team_id, user_id); // team_id:user_id:user

        token_store.set(&bot_token_key, bot_token).unwrap();
        token_store.set(&user_token_key, user_token).unwrap();

        // Verify bot token is stored at team_id:user_id
        assert_eq!(token_store.get(&bot_token_key).unwrap(), bot_token);
        assert_eq!(bot_token_key, "T123:U456");

        // Verify user token is stored at team_id:user_id:user
        assert_eq!(token_store.get(&user_token_key).unwrap(), user_token);
        assert_eq!(user_token_key, "T123:U456:user");

        // Verify they are different keys
        assert_ne!(bot_token_key, user_token_key);
    }

    #[test]
    #[serial_test::serial]
    fn test_status_shows_token_store_backend_file() {
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("profiles.json");
        let tokens_path = temp_dir.path().join("tokens.json");

        // Set up file backend
        std::env::set_var("SLACK_RS_TOKENS_PATH", tokens_path.to_str().unwrap());

        // Create a test profile
        let mut config = ProfilesConfig::new();
        config.set(
            "test".to_string(),
            Profile {
                team_id: "T123".to_string(),
                user_id: "U456".to_string(),
                team_name: Some("Test Team".to_string()),
                user_name: None,
                client_id: None,
                redirect_uri: None,
                scopes: None,
                bot_scopes: None,
                user_scopes: None,
                default_token_type: None,
            },
        );
        save_config(&config_path, &config).unwrap();

        // Note: We can't easily capture stdout in tests, but we verify the function doesn't panic
        // The actual output verification would require integration tests
        std::env::set_var("SLACK_RS_CONFIG_PATH", config_path.to_str().unwrap());

        // This test verifies that status() doesn't panic with file backend
        // The actual output contains "Token Store: file" but we can't easily verify stdout here

        std::env::remove_var("SLACK_RS_TOKENS_PATH");
        std::env::remove_var("SLACK_RS_CONFIG_PATH");
    }

    #[test]
    #[serial_test::serial]
    fn test_status_shows_slack_token_env_when_set() {
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("profiles.json");

        // Create a test profile
        let mut config = ProfilesConfig::new();
        config.set(
            "test".to_string(),
            Profile {
                team_id: "T123".to_string(),
                user_id: "U456".to_string(),
                team_name: Some("Test Team".to_string()),
                user_name: None,
                client_id: None,
                redirect_uri: None,
                scopes: None,
                bot_scopes: None,
                user_scopes: None,
                default_token_type: None,
            },
        );
        save_config(&config_path, &config).unwrap();

        // Set SLACK_TOKEN
        std::env::set_var("SLACK_TOKEN", "xoxb-secret-token");

        // status() should show "SLACK_TOKEN: set" without revealing the value
        // Note: We can't easily capture stdout in unit tests, but we verify no panic

        std::env::remove_var("SLACK_TOKEN");
    }

    // Tests for compute_default_token_type_display
    #[test]
    fn test_status_default_token_type_user_set() {
        // When profile.default_token_type is set to User, display "User"
        let result = compute_default_token_type_display(
            Some(crate::profile::TokenType::User),
            false, // has_user_token doesn't matter when profile default is set
        );
        assert_eq!(result, "User");
    }

    #[test]
    fn test_status_default_token_type_bot_set() {
        // When profile.default_token_type is set to Bot, display "Bot"
        let result = compute_default_token_type_display(
            Some(crate::profile::TokenType::Bot),
            true, // has_user_token doesn't matter when profile default is set
        );
        assert_eq!(result, "Bot");
    }

    #[test]
    fn test_status_default_token_type_fallback_with_user_token() {
        // When profile.default_token_type is unset and user token exists, display "User"
        let result = compute_default_token_type_display(None, true);
        assert_eq!(result, "User");
    }

    #[test]
    fn test_status_default_token_type_fallback_without_user_token() {
        // When profile.default_token_type is unset and no user token exists, display "Bot"
        let result = compute_default_token_type_display(None, false);
        assert_eq!(result, "Bot");
    }

    #[test]
    fn test_status_default_token_type_user_overrides_inference() {
        // Verify that profile.default_token_type=User takes priority over token inference
        // Even when user token is not available
        let result = compute_default_token_type_display(
            Some(crate::profile::TokenType::User),
            false, // No user token, but profile says User
        );
        assert_eq!(result, "User");
    }

    #[test]
    fn test_status_default_token_type_bot_overrides_inference() {
        // Verify that profile.default_token_type=Bot takes priority over token inference
        // Even when user token is available
        let result = compute_default_token_type_display(
            Some(crate::profile::TokenType::Bot),
            true, // User token available, but profile says Bot
        );
        assert_eq!(result, "Bot");
    }

    #[test]
    fn test_compute_initial_default_token_type_new_profile_with_user_token() {
        // New profile with user token should default to User
        let result = compute_initial_default_token_type(None, true);
        assert_eq!(result, crate::profile::TokenType::User);
    }

    #[test]
    fn test_compute_initial_default_token_type_new_profile_without_user_token() {
        // New profile without user token should default to Bot
        let result = compute_initial_default_token_type(None, false);
        assert_eq!(result, crate::profile::TokenType::Bot);
    }

    #[test]
    fn test_compute_initial_default_token_type_preserves_existing_bot() {
        // Existing profile with Bot default should be preserved even with user token
        let result = compute_initial_default_token_type(
            Some(crate::profile::TokenType::Bot),
            true, // User token available
        );
        assert_eq!(result, crate::profile::TokenType::Bot);
    }

    #[test]
    fn test_compute_initial_default_token_type_preserves_existing_user() {
        // Existing profile with User default should be preserved even without user token
        let result = compute_initial_default_token_type(
            Some(crate::profile::TokenType::User),
            false, // No user token
        );
        assert_eq!(result, crate::profile::TokenType::User);
    }

    /// Test that FileTokenStore::default_path() respects XDG_DATA_HOME
    /// This verifies the path resolution that auth status displays
    #[test]
    #[serial_test::serial]
    fn test_file_token_store_respects_xdg_data_home() {
        use crate::profile::FileTokenStore;
        use tempfile::TempDir;

        // Clear SLACK_RS_TOKENS_PATH to test XDG_DATA_HOME
        std::env::remove_var("SLACK_RS_TOKENS_PATH");

        let temp_dir = TempDir::new().unwrap();
        let xdg_data_home = temp_dir.path().to_str().unwrap();
        std::env::set_var("XDG_DATA_HOME", xdg_data_home);

        let path = FileTokenStore::default_path().unwrap();
        let expected = temp_dir.path().join("slack-rs").join("tokens.json");

        assert_eq!(
            path, expected,
            "auth status should display XDG_DATA_HOME-based path when XDG_DATA_HOME is set"
        );

        std::env::remove_var("XDG_DATA_HOME");
    }

    /// Test that SLACK_RS_TOKENS_PATH takes priority over XDG_DATA_HOME in auth status
    #[test]
    #[serial_test::serial]
    fn test_file_token_store_slack_rs_tokens_path_priority() {
        use crate::profile::FileTokenStore;
        use tempfile::TempDir;

        let temp_dir = TempDir::new().unwrap();
        let custom_path = temp_dir.path().join("custom-tokens.json");
        let xdg_data_home = temp_dir.path().join("xdg-data");

        // Set both environment variables
        std::env::set_var("SLACK_RS_TOKENS_PATH", custom_path.to_str().unwrap());
        std::env::set_var("XDG_DATA_HOME", xdg_data_home.to_str().unwrap());

        let path = FileTokenStore::default_path().unwrap();

        assert_eq!(
            path, custom_path,
            "auth status should display SLACK_RS_TOKENS_PATH when both env vars are set"
        );

        std::env::remove_var("SLACK_RS_TOKENS_PATH");
        std::env::remove_var("XDG_DATA_HOME");
    }
}