quetty 0.1.9

Terminal-based Azure Service Bus queue manager with intuitive TUI interface
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
use crate::app::managers::state_manager::AppState;
use crate::app::model::Model;
use crate::components::common::{ComponentId, ConfigActivityMsg, ConfigUpdateData, Msg};
use crate::config::azure::{clear_master_password, set_master_password};
use crate::constants::env_vars::*;
use crate::error::AppResult;
use crate::utils::encryption::ConnectionStringEncryption;
use quetty_server::encryption::ClientSecretEncryption;
use std::env;
use std::fs;
use std::sync::Mutex;
use tuirealm::terminal::TerminalAdapter;

/// Thread-safe environment variable management
/// This provides a safe wrapper around env::set_var to prevent data races
static ENV_LOCK: Mutex<()> = Mutex::new(());

/// Safe wrapper for setting environment variables
/// This prevents data races by using a mutex lock and handles lock poisoning
fn safe_set_env_var(key: &str, value: &str) -> AppResult<()> {
    let _lock = ENV_LOCK.lock().map_err(|e| {
        crate::error::AppError::State(format!("Environment variable lock poisoned: {e}"))
    })?;
    unsafe {
        env::set_var(key, value);
    }
    Ok(())
}

/// Safe wrapper for removing environment variables
/// This prevents data races by using a mutex lock and handles lock poisoning
fn safe_remove_env_var(key: &str) -> AppResult<()> {
    let _lock = ENV_LOCK.lock().map_err(|e| {
        crate::error::AppError::State(format!("Environment variable lock poisoned: {e}"))
    })?;
    unsafe {
        env::remove_var(key);
    }
    Ok(())
}

// Constants for placeholder and error messages
const PLACEHOLDER_ENCRYPTED_CONNECTION_STRING: &str = "<<encrypted-connection-string-present>>";
const PLACEHOLDER_ENCRYPTED_CLIENT_SECRET: &str = "<<encrypted-client-secret-present>>";
const ERROR_MASTER_PASSWORD_REQUIRED: &str =
    "Master password required for connection string authentication";
const ERROR_MASTER_PASSWORD_REQUIRED_CLIENT_SECRET: &str =
    "Master password required for client secret authentication";
// Profile names - using default profile for now
const DEFAULT_PROFILE_NAME: &str = "default";

impl<T> Model<T>
where
    T: TerminalAdapter,
{
    /// Handle configuration-related messages from the UI
    ///
    /// Processes configuration save, confirm-and-proceed, and cancel operations.
    /// This includes validating configuration data, encrypting sensitive values,
    /// writing to environment variables and .env files, and determining next actions.
    ///
    /// # Arguments
    /// * `msg` - The configuration activity message to process
    ///
    /// # Returns
    /// * `Ok(Some(Msg))` - Next UI action to take
    /// * `Ok(None)` - No further action needed
    /// * `Err(AppError)` - Configuration processing failed
    pub fn update_config(&mut self, msg: ConfigActivityMsg) -> AppResult<Option<Msg>> {
        match msg {
            ConfigActivityMsg::Save(config_data) => self.handle_config_save(config_data),
            ConfigActivityMsg::ConfirmAndProceed(config_data) => {
                self.handle_config_confirm_and_proceed(config_data)
            }
            ConfigActivityMsg::Cancel => self.handle_config_cancel(),
        }
    }

    fn handle_config_save(&mut self, config_data: ConfigUpdateData) -> AppResult<Option<Msg>> {
        log::info!(
            "Saving configuration with auth method: {}",
            config_data.auth_method
        );

        log::debug!(
            "ConfigUpdateData: tenant_id={:?}, client_id={:?}, connection_string={:?}",
            config_data
                .tenant_id
                .as_ref()
                .map(|s| if s.is_empty() { "<empty>" } else { "<set>" }),
            config_data
                .client_id
                .as_ref()
                .map(|s| if s.is_empty() { "<empty>" } else { "<set>" }),
            config_data
                .connection_string
                .as_ref()
                .map(|s| if s.is_empty() { "<empty>" } else { "<set>" })
        );

        // Validate that client secret auth method requires master password for encryption
        if config_data.auth_method == "client_secret" {
            if let Some(client_secret) = &config_data.client_secret {
                if !client_secret.trim().is_empty()
                    && !client_secret.contains(PLACEHOLDER_ENCRYPTED_CLIENT_SECRET)
                    && config_data.master_password.is_none()
                {
                    log::error!(
                        "Client secret provided without master password - encryption required"
                    );
                    return Err(crate::error::AppError::Config(
                        "Master password is required when providing a client secret for encryption"
                            .to_string(),
                    ));
                }
            }
        }

        // Save sensitive data to environment variables (which will be written to .env)
        if let Some(tenant_id) = &config_data.tenant_id {
            safe_set_env_var(AZURE_AD_TENANT_ID, tenant_id)?;
        }
        if let Some(client_id) = &config_data.client_id {
            safe_set_env_var(AZURE_AD_CLIENT_ID, client_id)?;
        }
        // Note: client_secret is handled separately in encryption section below to ensure it's always encrypted
        if let Some(subscription_id) = &config_data.subscription_id {
            safe_set_env_var(AZURE_AD_SUBSCRIPTION_ID, subscription_id)?;
        }
        if let Some(resource_group) = &config_data.resource_group {
            safe_set_env_var(AZURE_AD_RESOURCE_GROUP, resource_group)?;
        }
        if let Some(namespace) = &config_data.namespace {
            safe_set_env_var(AZURE_AD_NAMESPACE, namespace)?;
        }

        // Handle connection string encryption
        if let Some(master_password) = &config_data.master_password {
            // Set master password for runtime decryption
            set_master_password(master_password.clone());

            // Check if we need to encrypt a new connection string
            if let Some(connection_string) = &config_data.connection_string {
                if !connection_string.trim().is_empty()
                    && !connection_string.contains(PLACEHOLDER_ENCRYPTED_CONNECTION_STRING)
                {
                    // New connection string provided - encrypt it
                    log::info!("New connection string provided, encrypting with master password");
                    let encryption = ConnectionStringEncryption::new();
                    match encryption.encrypt_connection_string(connection_string, master_password) {
                        Ok(encrypted) => {
                            safe_set_env_var(SERVICEBUS_ENCRYPTED_CONNECTION_STRING, &encrypted)?;
                            safe_set_env_var(
                                SERVICEBUS_ENCRYPTION_SALT,
                                &encryption.salt_base64(),
                            )?;
                        }
                        Err(e) => {
                            log::error!("Failed to encrypt connection string: {e}");
                            return Err(crate::error::AppError::Config(format!(
                                "Connection string encryption failed: {e}"
                            )));
                        }
                    }
                } else {
                    log::info!(
                        "Using existing encrypted connection string with provided master password"
                    );
                }
            }

            // Check if we need to encrypt a new client secret
            if let Some(client_secret) = &config_data.client_secret {
                if !client_secret.trim().is_empty()
                    && !client_secret.contains(PLACEHOLDER_ENCRYPTED_CLIENT_SECRET)
                {
                    // New client secret provided - encrypt it
                    log::info!("New client secret provided, encrypting with master password");
                    let encryption = quetty_server::encryption::ClientSecretEncryption::new();
                    match encryption.encrypt_client_secret(client_secret, master_password) {
                        Ok(encrypted) => {
                            safe_set_env_var(AZURE_AD_ENCRYPTED_CLIENT_SECRET, &encrypted)?;
                            safe_set_env_var(
                                AZURE_AD_CLIENT_SECRET_ENCRYPTION_SALT,
                                &encryption.salt_base64(),
                            )?;
                            // Remove any plain text client secret
                            safe_remove_env_var(AZURE_AD_CLIENT_SECRET)?;
                        }
                        Err(e) => {
                            log::error!("Failed to encrypt client secret: {e}");
                            return Err(crate::error::AppError::Config(format!(
                                "Client secret encryption failed: {e}"
                            )));
                        }
                    }
                } else {
                    log::info!(
                        "Using existing encrypted client secret with provided master password"
                    );
                }
            }

            // Handle decryption of encrypted client secret for runtime use
            if std::env::var(AZURE_AD_ENCRYPTED_CLIENT_SECRET).is_ok()
                && std::env::var(AZURE_AD_CLIENT_SECRET_ENCRYPTION_SALT).is_ok()
            {
                match self.decrypt_and_set_client_secret(master_password) {
                    Ok(_) => log::info!("Client secret decrypted and set for runtime use"),
                    Err(e) => {
                        log::error!("Failed to decrypt client secret: {e}");
                        return Err(e);
                    }
                }
            }

            if config_data.connection_string.is_none() {
                log::info!("Master password set for existing encrypted connection string");
            }
        }

        // Write environment variables to .env file
        if let Err(e) = self.write_env_file(&config_data) {
            log::error!("Failed to write .env file: {e}");
            return Err(e);
        }

        // Update config.toml with auth_method and other non-sensitive settings
        if let Err(e) = self.update_config_toml(&config_data) {
            log::error!("Failed to update config.toml: {e}");
            return Err(e);
        }

        log::info!("Configuration saved successfully.");
        Ok(Some(Msg::ShowSuccess(
            "Configuration saved successfully.".to_string(),
        )))
    }

    fn handle_config_cancel(&mut self) -> AppResult<Option<Msg>> {
        log::debug!("Config/password popup cancelled");

        // Clear any pending config data
        self.state_manager.pending_config_data = None;

        // Check which component is mounted and unmount appropriately
        if self.app.mounted(&ComponentId::ConfigScreen) {
            if let Err(e) = self.unmount_config_screen() {
                self.error_reporter
                    .report_mount_error("ConfigScreen", "unmount", e);
            }
        }

        if self.app.mounted(&ComponentId::PasswordPopup) {
            if let Err(e) = self.unmount_password_popup() {
                self.error_reporter
                    .report_mount_error("PasswordPopup", "unmount", e);
            }

            // When password popup is cancelled, offer to open config screen instead
            return Ok(Some(Msg::ToggleConfigScreen));
        }

        Ok(None)
    }

    fn handle_config_confirm_and_proceed(
        &mut self,
        mut config_data: ConfigUpdateData,
    ) -> AppResult<Option<Msg>> {
        log::info!(
            "Confirming and proceeding with configuration - auth method: {}",
            config_data.auth_method
        );

        // Merge with pending config data if available
        self.merge_pending_config_data(&mut config_data);

        self.log_config_data(&config_data);

        // Global change detection - check if anything actually changed before proceeding
        let current_config = crate::config::get_config_or_panic();
        let config_changed = self.has_config_changed(current_config, &config_data);

        if !config_changed {
            log::info!(
                "No configuration changes detected for any auth method - skipping all operations"
            );
            // Just close the config screen and return success message
            if let Err(e) = self.unmount_config_screen() {
                self.error_reporter
                    .report_mount_error("ConfigScreen", "unmount", e);
            }
            return Ok(Some(Msg::ShowSuccess(
                "Configuration unchanged - no update needed.".to_string(),
            )));
        }

        log::info!("Configuration changes detected - proceeding with update flow");

        // Handle password validation and encryption
        if let Some(master_password) = &config_data.master_password {
            if let Some(msg) = self.handle_password_and_encryption(&config_data, master_password)? {
                return Ok(Some(msg));
            }
        } else if config_data.auth_method == "connection_string" {
            // Connection string auth requires master password
            let config = crate::config::get_config_or_panic();
            if config.servicebus().has_connection_string() {
                // We have encrypted connection string but no password provided
                // First update the auth method in config.toml, then show password popup
                log::info!(
                    "Connection string auth selected but no password provided - updating config and showing password popup"
                );

                // Store the config data from the config screen for later use
                self.state_manager.pending_config_data = Some(config_data.clone());

                // Update auth method in config.toml first
                if let Err(e) = self.update_config_toml(&config_data) {
                    log::error!("Failed to update config.toml: {e}");
                    return Err(e);
                }

                // Reload configuration to pick up the auth method change
                if let Err(e) = crate::config::reload_config() {
                    log::error!("Failed to reload configuration: {e}");
                    return Err(crate::error::AppError::Config(format!(
                        "Configuration reload failed: {e}"
                    )));
                }

                // Close config screen first
                if let Err(e) = self.unmount_config_screen() {
                    self.error_reporter
                        .report_mount_error("ConfigScreen", "unmount", e);
                }

                // Show password popup
                if let Err(e) =
                    self.mount_password_popup(Some(ERROR_MASTER_PASSWORD_REQUIRED.to_string()))
                {
                    self.error_reporter
                        .report_mount_error("PasswordPopup", "mount", &e);
                    return Ok(Some(Msg::ToggleConfigScreen));
                }

                self.set_redraw(true);
                return Ok(None);
            } else {
                // No encrypted connection string exists - need to configure connection string
                // Keep the config screen open so user can enter connection string and password
                log::info!(
                    "Connection string auth selected but no encrypted connection string exists - user needs to configure"
                );
            }
        } else if config_data.auth_method == "client_secret" {
            // Client secret auth requires master password if encrypted client secret exists
            if std::env::var(AZURE_AD_ENCRYPTED_CLIENT_SECRET).is_ok() {
                // We have encrypted client secret but no password provided
                // First update the auth method in config.toml, then show password popup
                log::info!(
                    "Client secret auth selected but no password provided - updating config and showing password popup"
                );

                // Store the config data from the config screen for later use
                self.state_manager.pending_config_data = Some(config_data.clone());

                // Update auth method in config.toml first
                if let Err(e) = self.update_config_toml(&config_data) {
                    log::error!("Failed to update config.toml: {e}");
                    return Err(e);
                }

                // Reload configuration to pick up the auth method change
                if let Err(e) = crate::config::reload_config() {
                    log::error!("Failed to reload configuration: {e}");
                    return Err(crate::error::AppError::Config(format!(
                        "Configuration reload failed: {e}"
                    )));
                }

                // Close config screen first
                if let Err(e) = self.unmount_config_screen() {
                    self.error_reporter
                        .report_mount_error("ConfigScreen", "unmount", e);
                }

                // Show password popup for client secret decryption
                if let Err(e) = self.mount_password_popup(Some(
                    ERROR_MASTER_PASSWORD_REQUIRED_CLIENT_SECRET.to_string(),
                )) {
                    self.error_reporter
                        .report_mount_error("PasswordPopup", "mount", &e);
                    return Ok(Some(Msg::ToggleConfigScreen));
                }

                self.set_redraw(true);
                return Ok(None);
            } else {
                // No encrypted client secret exists - need to configure client secret
                // Keep the config screen open so user can enter client secret and password
                log::info!(
                    "Client secret auth selected but no encrypted client secret exists - user needs to configure"
                );
            }
        }

        // Persist configuration
        self.persist_configuration(&config_data)?;

        // Handle UI cleanup and determine next action
        self.cleanup_and_determine_next_action(&config_data)
    }

    /// Merge pending config data from config screen with current data
    fn merge_pending_config_data(&mut self, config_data: &mut ConfigUpdateData) {
        if let Some(pending_data) = &self.state_manager.pending_config_data {
            log::info!("Merging pending config data from config screen with password popup data");

            // Helper macro to merge optional fields
            macro_rules! merge_field {
                ($field:ident) => {
                    if config_data.$field.is_none() && pending_data.$field.is_some() {
                        config_data.$field = pending_data.$field.clone();
                    }
                };
            }

            // Merge auth method (always use pending data if available)
            config_data.auth_method = pending_data.auth_method.clone();
            log::info!(
                "Merged auth method from pending config data: '{}'",
                config_data.auth_method
            );

            // Merge all configuration fields
            merge_field!(tenant_id);
            merge_field!(client_id);
            merge_field!(client_secret);
            merge_field!(subscription_id);
            merge_field!(resource_group);
            merge_field!(namespace);
            merge_field!(connection_string);

            // Special handling for queue name with logging
            if config_data.queue_name.is_none() && pending_data.queue_name.is_some() {
                config_data.queue_name = pending_data.queue_name.clone();
                log::info!(
                    "Preserved queue name from config screen: {:?}",
                    config_data.queue_name
                );
            }

            // Clear the pending config data after merging
            self.state_manager.pending_config_data = None;
        }
    }

    fn log_config_data(&self, config_data: &ConfigUpdateData) {
        log::debug!(
            "ConfigUpdateData: tenant_id={:?}, client_id={:?}, connection_string={:?}",
            config_data
                .tenant_id
                .as_ref()
                .map(|s| if s.is_empty() { "<empty>" } else { "<set>" }),
            config_data
                .client_id
                .as_ref()
                .map(|s| if s.is_empty() { "<empty>" } else { "<set>" }),
            config_data
                .connection_string
                .as_ref()
                .map(|s| if s.is_empty() { "<empty>" } else { "<set>" })
        );
    }

    fn handle_password_and_encryption(
        &mut self,
        config_data: &ConfigUpdateData,
        master_password: &str,
    ) -> AppResult<Option<Msg>> {
        match config_data.auth_method.as_str() {
            "connection_string" => {
                if config_data.connection_string.is_none() {
                    // Password popup mode - validate connection string password
                    self.validate_master_password(master_password)
                } else {
                    // Config screen mode - handle connection string encryption
                    self.handle_connection_string_encryption(config_data, master_password)
                }
            }
            "client_secret" => {
                // Check if we're in password popup mode by looking at current app state
                if self.state_manager.app_state
                    == crate::app::managers::state_manager::AppState::PasswordPopup
                {
                    // Password popup mode - validate client secret password
                    self.validate_client_secret_password(master_password)
                } else if config_data.client_secret.is_some() {
                    // Config screen mode - handle client secret encryption
                    self.handle_client_secret_encryption(config_data, master_password)
                } else {
                    // No client secret provided and not in password popup mode
                    Ok(None)
                }
            }
            _ => {
                // Other auth methods don't need password/encryption handling
                Ok(None)
            }
        }
    }

    fn handle_client_secret_encryption(
        &mut self,
        config_data: &ConfigUpdateData,
        _master_password: &str,
    ) -> AppResult<Option<Msg>> {
        log::info!("Client secret auth - handling client secret encryption");

        // Directly handle the client secret configuration without recursion
        // This skips the password handling logic and goes straight to saving
        self.save_client_secret_config(config_data)
    }

    fn save_client_secret_config(
        &mut self,
        config_data: &ConfigUpdateData,
    ) -> AppResult<Option<Msg>> {
        log::info!("Saving client secret configuration directly");

        // First encrypt the client secret if provided
        if let Some(client_secret) = &config_data.client_secret {
            if let Some(master_password) = &config_data.master_password {
                if !client_secret.trim().is_empty()
                    && !client_secret.contains(PLACEHOLDER_ENCRYPTED_CLIENT_SECRET)
                    && !master_password.trim().is_empty()
                {
                    log::info!("Encrypting client secret with master password");
                    let encryption = quetty_server::encryption::ClientSecretEncryption::new();
                    match encryption.encrypt_client_secret(client_secret, master_password) {
                        Ok(encrypted) => {
                            safe_set_env_var(AZURE_AD_ENCRYPTED_CLIENT_SECRET, &encrypted)?;
                            safe_set_env_var(
                                AZURE_AD_CLIENT_SECRET_ENCRYPTION_SALT,
                                &encryption.salt_base64(),
                            )?;
                            safe_remove_env_var(AZURE_AD_CLIENT_SECRET)?;
                            log::info!("Client secret encrypted successfully");

                            // Immediately decrypt the client secret for runtime use
                            if let Some(master_password) = &config_data.master_password {
                                match self.decrypt_and_set_client_secret(master_password) {
                                    Ok(_) => log::info!(
                                        "Client secret decrypted and set for runtime use"
                                    ),
                                    Err(e) => {
                                        log::error!(
                                            "Failed to decrypt newly encrypted client secret: {e}"
                                        );
                                        return Err(e);
                                    }
                                }
                            }
                        }
                        Err(e) => {
                            log::error!("Failed to encrypt client secret: {e}");
                            return Err(crate::error::AppError::Config(format!(
                                "Client secret encryption failed: {e}"
                            )));
                        }
                    }
                }
            }
        }

        // Call the main config saving logic that handles file writing
        self.persist_configuration(config_data)?;

        // Handle UI cleanup and determine next action (authentication)
        self.cleanup_and_determine_next_action(config_data)
    }

    fn validate_master_password(&mut self, master_password: &str) -> AppResult<Option<Msg>> {
        log::info!("Password popup mode - validating master password");

        let config = crate::config::get_config_or_panic();
        set_master_password(master_password.to_string());

        match config.servicebus().connection_string() {
            Ok(Some(_)) => {
                log::info!("Password validation successful - connection string decrypted");

                // Check if we have pending config data with queue name that needs to be saved
                if let Some(pending_config) = &self.state_manager.pending_config_data {
                    if pending_config.queue_name.is_some() {
                        log::info!("Saving queue name from pending config data to .env file");

                        // Create a minimal config data with just the queue name for saving
                        let queue_config_data = crate::components::common::ConfigUpdateData {
                            auth_method: crate::utils::auth::AUTH_METHOD_CONNECTION_STRING
                                .to_string(),
                            tenant_id: None,
                            client_id: None,
                            client_secret: None,
                            subscription_id: None,
                            resource_group: None,
                            namespace: None,
                            connection_string: None,
                            master_password: None,
                            queue_name: pending_config.queue_name.clone(),
                        };

                        // Save queue name to environment and .env file
                        if let Some(queue_name) = &queue_config_data.queue_name {
                            safe_set_env_var(SERVICEBUS_QUEUE_NAME, queue_name)?;
                            log::info!("Set queue name in environment: '{queue_name}'");
                        }

                        // Write to .env file
                        if let Err(e) = self.write_env_file(&queue_config_data) {
                            log::error!("Failed to write queue name to .env file: {e}");
                        } else {
                            log::info!("Queue name saved to .env file successfully");
                        }

                        // Clear pending config data since we've processed it
                        self.state_manager.pending_config_data = None;
                    }
                }

                // Reset authenticating flag since password is now valid
                self.state_manager.is_authenticating = false;
                Ok(None)
            }
            Ok(None) => {
                log::error!("Password validation failed - no connection string found");
                // Clear the password since there's no connection string to decrypt
                clear_master_password();

                self.state_manager.is_authenticating = true;

                if let Err(e) = self.unmount_password_popup() {
                    self.error_reporter
                        .report_mount_error("PasswordPopup", "unmount", e);
                }
                // Show config screen since there's no encrypted connection string configured
                Ok(Some(Msg::ToggleConfigScreen))
            }
            Err(e) => {
                log::error!("Password validation failed - decryption error: {e}");
                // Clear the incorrect password to prevent further issues
                clear_master_password();

                // Set authenticating flag to prevent namespace loading from starting
                self.state_manager.is_authenticating = true;
                if let Err(e) = self.mount_password_popup(Some(
                    "Invalid master password. Please try again or update configuration."
                        .to_string(),
                )) {
                    self.error_reporter
                        .report_mount_error("PasswordPopup", "mount", e);
                    // If we can't mount password popup, show config screen instead
                    return Ok(Some(Msg::ToggleConfigScreen));
                }

                self.set_redraw(true);

                // Return a message to stop the flow and prevent persist_configuration from running
                Ok(Some(Msg::ForceRedraw))
            }
        }
    }

    fn validate_client_secret_password(&mut self, master_password: &str) -> AppResult<Option<Msg>> {
        log::info!("Password popup mode - validating client secret password");

        // Set master password for runtime decryption
        set_master_password(master_password.to_string());

        // Try to decrypt the client secret to validate the password
        match self.decrypt_and_set_client_secret(master_password) {
            Ok(_) => {
                log::info!("Password validation successful - client secret decrypted");

                // Check if we have pending config data with queue name that needs to be saved
                if let Some(pending_config) = &self.state_manager.pending_config_data {
                    if pending_config.queue_name.is_some() {
                        log::info!("Saving queue name from pending config data to .env file");

                        // Create a minimal config data with just the queue name for saving
                        let queue_config_data = crate::components::common::ConfigUpdateData {
                            auth_method: crate::utils::auth::AUTH_METHOD_CLIENT_SECRET.to_string(),
                            tenant_id: None,
                            client_id: None,
                            client_secret: None,
                            subscription_id: None,
                            resource_group: None,
                            namespace: None,
                            connection_string: None,
                            master_password: None,
                            queue_name: pending_config.queue_name.clone(),
                        };

                        // Save queue name to environment and .env file
                        if let Some(queue_name) = &queue_config_data.queue_name {
                            safe_set_env_var(SERVICEBUS_QUEUE_NAME, queue_name)?;
                            log::info!("Set queue name in environment: '{queue_name}'");
                        }

                        // Write to .env file
                        if let Err(e) = self.write_env_file(&queue_config_data) {
                            log::error!("Failed to write queue name to .env file: {e}");
                        } else {
                            log::info!("Queue name saved to .env file successfully");
                        }

                        // Clear pending config data since we've processed it
                        self.state_manager.pending_config_data = None;
                    }
                }

                // Close password popup and proceed with authentication
                log::info!(
                    "Closing password popup and proceeding with client secret authentication"
                );
                if let Err(e) = self.unmount_password_popup() {
                    self.error_reporter
                        .report_mount_error("PasswordPopup", "unmount", e);
                }

                // Recreate auth service to pick up the decrypted client secret
                log::info!("Recreating auth service with decrypted client secret");
                if let Err(e) = self.create_auth_service() {
                    log::error!(
                        "Failed to recreate auth service after client secret decryption: {e}"
                    );
                    return Err(e);
                }

                // Keep authenticating flag true since we're about to start authentication
                // It will be cleared when authentication succeeds or fails

                // Proceed with authentication
                Ok(Some(Msg::AuthActivity(
                    crate::components::common::AuthActivityMsg::Login,
                )))
            }
            Err(e) => {
                log::error!("Password validation failed - decryption error: {e}");
                // Clear the incorrect password to prevent further issues
                clear_master_password();

                // Set authenticating flag to prevent namespace loading from starting
                self.state_manager.is_authenticating = true;
                if let Err(e) = self.mount_password_popup(Some(
                    "Invalid master password. Please try again or update configuration."
                        .to_string(),
                )) {
                    self.error_reporter
                        .report_mount_error("PasswordPopup", "mount", e);
                    // If we can't mount password popup, show config screen instead
                    return Ok(Some(Msg::ToggleConfigScreen));
                }

                self.set_redraw(true);

                // Return a message to stop the flow and prevent persist_configuration from running
                Ok(Some(Msg::ForceRedraw))
            }
        }
    }

    fn handle_connection_string_encryption(
        &mut self,
        config_data: &ConfigUpdateData,
        master_password: &str,
    ) -> AppResult<Option<Msg>> {
        set_master_password(master_password.to_string());

        if let Some(connection_string) = &config_data.connection_string {
            if !connection_string.trim().is_empty()
                && !connection_string.contains(PLACEHOLDER_ENCRYPTED_CONNECTION_STRING)
            {
                // New connection string - encrypt it
                log::info!("New connection string provided, encrypting with master password");
                let encryption = ConnectionStringEncryption::new();
                match encryption.encrypt_connection_string(connection_string, master_password) {
                    Ok(encrypted) => {
                        safe_set_env_var(SERVICEBUS_ENCRYPTED_CONNECTION_STRING, &encrypted)?;
                        safe_set_env_var(SERVICEBUS_ENCRYPTION_SALT, &encryption.salt_base64())?;
                    }
                    Err(e) => {
                        log::error!("Failed to encrypt connection string: {e}");
                        return Err(crate::error::AppError::Config(format!(
                            "Connection string encryption failed: {e}"
                        )));
                    }
                }
            } else if connection_string.contains(PLACEHOLDER_ENCRYPTED_CONNECTION_STRING) {
                // Placeholder with password - verify password works with existing connection string
                log::info!("Placeholder connection string with password - verifying password");

                let config = crate::config::get_config_or_panic();
                match config.servicebus().connection_string() {
                    Ok(Some(_)) => {
                        // Password works with existing connection string - this is just password entry, not a change
                        log::info!("Password works with existing encrypted connection string");
                    }
                    Ok(None) => {
                        log::warn!("No encrypted connection string found despite placeholder");
                    }
                    Err(_) => {
                        // Password doesn't work - this is a password change
                        log::info!(
                            "Password doesn't work with existing connection string - clearing for new setup"
                        );
                        safe_remove_env_var(SERVICEBUS_ENCRYPTED_CONNECTION_STRING)?;
                        safe_remove_env_var(SERVICEBUS_ENCRYPTION_SALT)?;
                        return Err(crate::error::AppError::Config(
                            "Master password doesn't match existing encrypted connection string. Please enter your connection string again.".to_string()
                        ));
                    }
                }
            } else {
                log::info!(
                    "Using existing encrypted connection string with provided master password"
                );
            }
        } else {
            // Password change scenario
            let config = crate::config::get_config_or_panic();
            if config.servicebus().has_connection_string() {
                log::info!(
                    "Master password provided without connection string - assuming password change"
                );
                safe_remove_env_var(SERVICEBUS_ENCRYPTED_CONNECTION_STRING)?;
                safe_remove_env_var(SERVICEBUS_ENCRYPTION_SALT)?;
                return Err(crate::error::AppError::Config(
                    "Master password changed. Please enter your connection string again for security.".to_string()
                ));
            } else {
                log::info!("Master password set but no connection string available");
            }
        }

        Ok(None)
    }

    fn persist_configuration(&mut self, config_data: &ConfigUpdateData) -> AppResult<()> {
        // Get current configuration before changes to detect what actually changed
        let current_config = crate::config::get_config_or_panic();
        let previous_auth_method = current_config.azure_ad().auth_method.clone();

        // Check if configuration actually changed by comparing key values
        let config_changed = self.has_config_changed(current_config, config_data);

        if !config_changed {
            log::info!("No configuration changes detected - skipping reload and file operations");
            return Ok(());
        }

        log::info!("Configuration changes detected - proceeding with update");

        // Set environment variables
        self.set_environment_variables(config_data)?;

        // Write to files
        if let Err(e) = self.write_env_file(config_data) {
            log::error!("Failed to write .env file: {e}");
            return Err(e);
        }

        if let Err(e) = self.update_config_toml(config_data) {
            log::error!("Failed to update config.toml: {e}");
            return Err(e);
        }

        // Reload configuration
        if let Err(e) = crate::config::reload_config() {
            log::error!("Failed to reload configuration: {e}");
            return Err(crate::error::AppError::Config(format!(
                "Configuration reload failed: {e}"
            )));
        }

        // Invalidate profile cache to ensure fresh data after config changes
        crate::config::invalidate_profile_cache();
        log::debug!("Profile cache invalidated after config update");

        // Only recreate auth service if auth method actually changed
        if previous_auth_method != config_data.auth_method {
            log::info!(
                "Auth method changed from '{}' to '{}' - recreating auth service",
                previous_auth_method,
                config_data.auth_method
            );
            if let Err(e) = self.create_auth_service() {
                log::error!("Failed to create auth service: {e}");
                return Err(e);
            }
        } else {
            log::debug!(
                "Auth method unchanged ('{}') - skipping auth service recreation",
                config_data.auth_method
            );
        }

        Ok(())
    }

    /// Check if the configuration has actually changed compared to current values
    fn has_config_changed(
        &self,
        current_config: &crate::config::AppConfig,
        config_data: &ConfigUpdateData,
    ) -> bool {
        // Check auth method change
        if current_config.azure_ad().auth_method != config_data.auth_method {
            log::debug!(
                "Auth method changed: '{}' -> '{}'",
                current_config.azure_ad().auth_method,
                config_data.auth_method
            );
            return true;
        }

        // Get current environment values
        let current_tenant_id = std::env::var(AZURE_AD_TENANT_ID).ok();
        let current_client_id = std::env::var(AZURE_AD_CLIENT_ID).ok();
        let current_subscription_id = std::env::var(AZURE_AD_SUBSCRIPTION_ID).ok();
        let current_resource_group = std::env::var(AZURE_AD_RESOURCE_GROUP).ok();
        let current_namespace = std::env::var(AZURE_AD_NAMESPACE).ok();
        let current_queue_name = std::env::var(SERVICEBUS_QUEUE_NAME).ok();

        // Helper function to compare optional values (treating empty strings as None)
        let normalize_value = |value: &Option<String>| -> Option<String> {
            value.as_ref().and_then(|v| {
                if v.trim().is_empty() {
                    None
                } else {
                    Some(v.clone())
                }
            })
        };

        // Check each field for changes
        if normalize_value(&current_tenant_id) != normalize_value(&config_data.tenant_id) {
            log::debug!("Tenant ID changed");
            return true;
        }

        if normalize_value(&current_client_id) != normalize_value(&config_data.client_id) {
            log::debug!("Client ID changed");
            return true;
        }

        if normalize_value(&current_subscription_id)
            != normalize_value(&config_data.subscription_id)
        {
            log::debug!("Subscription ID changed");
            return true;
        }

        if normalize_value(&current_resource_group) != normalize_value(&config_data.resource_group)
        {
            log::debug!("Resource group changed");
            return true;
        }

        if normalize_value(&current_namespace) != normalize_value(&config_data.namespace) {
            log::debug!("Namespace changed");
            return true;
        }

        // Check queue name change only for connection string auth
        if config_data.auth_method == crate::utils::auth::AUTH_METHOD_CONNECTION_STRING
            && normalize_value(&current_queue_name) != normalize_value(&config_data.queue_name)
        {
            log::debug!("Queue name changed");
            return true;
        }

        // Check for new secrets being provided (existing encrypted secrets don't count as changes)
        if let Some(connection_string) = &config_data.connection_string {
            if !connection_string.trim().is_empty()
                && !connection_string.contains(PLACEHOLDER_ENCRYPTED_CONNECTION_STRING)
            {
                log::debug!("New connection string provided");
                return true;
            }
        }

        if let Some(client_secret) = &config_data.client_secret {
            if !client_secret.trim().is_empty()
                && !client_secret.contains(PLACEHOLDER_ENCRYPTED_CLIENT_SECRET)
            {
                log::debug!("New client secret provided");
                return true;
            }
        }

        // If master password is provided, it means user wants to update/verify encryption
        if config_data.master_password.is_some() {
            log::debug!("Master password provided - treating as potential configuration change");
            return true;
        }

        log::debug!("No configuration changes detected");
        false
    }

    fn set_environment_variables(&self, config_data: &ConfigUpdateData) -> AppResult<()> {
        if let Some(tenant_id) = &config_data.tenant_id {
            safe_set_env_var(AZURE_AD_TENANT_ID, tenant_id)?;
        }
        if let Some(client_id) = &config_data.client_id {
            safe_set_env_var(AZURE_AD_CLIENT_ID, client_id)?;
        }
        // Note: client_secret is handled separately in encryption section to ensure it's always encrypted
        if let Some(subscription_id) = &config_data.subscription_id {
            safe_set_env_var(AZURE_AD_SUBSCRIPTION_ID, subscription_id)?;
        }
        if let Some(resource_group) = &config_data.resource_group {
            safe_set_env_var(AZURE_AD_RESOURCE_GROUP, resource_group)?;
        }
        if let Some(namespace) = &config_data.namespace {
            safe_set_env_var(AZURE_AD_NAMESPACE, namespace)?;
        }

        // Set queue name only for connection string auth
        if config_data.auth_method == crate::utils::auth::AUTH_METHOD_CONNECTION_STRING {
            if let Some(queue_name) = &config_data.queue_name {
                if !queue_name.trim().is_empty() {
                    safe_set_env_var(SERVICEBUS_QUEUE_NAME, queue_name)?;
                    log::info!("Updated queue name from config screen: '{queue_name}'");
                }
            } else {
                log::debug!("No queue name provided in config screen");
            }
        }
        Ok(())
    }

    fn cleanup_and_determine_next_action(
        &mut self,
        config_data: &ConfigUpdateData,
    ) -> AppResult<Option<Msg>> {
        self.state_manager.is_authenticating = false;

        // Clear any pending config data since we're proceeding with the final configuration
        self.state_manager.pending_config_data = None;

        // Cleanup UI components
        if self.app.mounted(&ComponentId::ConfigScreen) {
            if let Err(e) = self.unmount_config_screen() {
                self.error_reporter
                    .report_mount_error("ConfigScreen", "unmount", e);
            }
        }
        if self.app.mounted(&ComponentId::PasswordPopup) {
            if let Err(e) = self.app.umount(&ComponentId::PasswordPopup) {
                self.error_reporter.report_mount_error(
                    "PasswordPopup",
                    "unmount",
                    crate::error::AppError::Component(e.to_string()),
                );
            } else {
                // Update app state to prevent view errors
                if self.state_manager.app_state == AppState::PasswordPopup {
                    self.state_manager.app_state = AppState::Loading;
                }
            }
        }

        // Determine next action based on auth method
        if config_data.auth_method == crate::utils::auth::AUTH_METHOD_CONNECTION_STRING {
            log::info!(
                "Configuration saved successfully. Creating Service Bus manager with connection string."
            );
            Ok(Some(Msg::AuthActivity(
                crate::components::common::AuthActivityMsg::CreateServiceBusManager,
            )))
        } else {
            log::info!("Configuration saved successfully. Proceeding to authentication.");
            Ok(Some(Msg::AuthActivity(
                crate::components::common::AuthActivityMsg::Login,
            )))
        }
    }

    /// Write configuration data to the .env file for persistence
    ///
    /// Parses existing .env file, updates specified values, and writes back to disk.
    /// This preserves existing comments and environment variables not managed by the app.
    /// Only writes non-empty values from the configuration data.
    ///
    /// # Arguments
    /// * `config_data` - Configuration data to persist to .env file
    ///
    /// # Returns
    /// * `Ok(())` - .env file updated successfully
    /// * `Err(AppError)` - File I/O or parsing error occurred
    pub fn write_env_file(&self, config_data: &ConfigUpdateData) -> AppResult<()> {
        // Use profile-based path resolution instead of hardcoded relative path
        let env_path = self.get_profile_env_path()?;

        // Parse existing .env file
        let (mut env_content, existing_values) = self.parse_existing_env_file(&env_path)?;

        // Update environment variables with new and existing values
        self.update_env_variables(&mut env_content, &existing_values, config_data);

        // Write the updated content to file
        self.write_env_content_to_file(&env_path, &env_content)
    }

    /// Parse existing .env file and extract managed environment variables
    fn parse_existing_env_file(
        &self,
        env_path: &str,
    ) -> AppResult<(String, std::collections::HashMap<String, String>)> {
        let mut env_content = String::new();
        let mut existing_values = std::collections::HashMap::new();

        if let Ok(existing_content) = fs::read_to_string(env_path) {
            for line in existing_content.lines() {
                let line = line.trim();

                // Preserve comments and empty lines
                if line.is_empty() || line.starts_with('#') {
                    env_content.push_str(line);
                    env_content.push('\n');
                    continue;
                }

                // Extract managed environment variables
                if let Some(eq_pos) = line.find('=') {
                    let key = &line[..eq_pos];
                    let value = &line[eq_pos + 1..];

                    if Self::is_managed_env_key(key) {
                        existing_values.insert(key.to_string(), value.to_string());
                        continue; // Skip this line, we'll add it back with new or existing value
                    }
                }

                // Preserve non-managed environment variables
                env_content.push_str(line);
                env_content.push('\n');
            }
        }

        Ok((env_content, existing_values))
    }

    /// Check if an environment variable key is managed by this application
    fn is_managed_env_key(key: &str) -> bool {
        matches!(
            key,
            AZURE_AD_TENANT_ID
                | AZURE_AD_CLIENT_ID
                | AZURE_AD_CLIENT_SECRET
                | AZURE_AD_ENCRYPTED_CLIENT_SECRET
                | AZURE_AD_CLIENT_SECRET_ENCRYPTION_SALT
                | AZURE_AD_SUBSCRIPTION_ID
                | AZURE_AD_RESOURCE_GROUP
                | AZURE_AD_NAMESPACE
                | SERVICEBUS_ENCRYPTED_CONNECTION_STRING
                | SERVICEBUS_ENCRYPTION_SALT
                | SERVICEBUS_QUEUE_NAME
        )
    }

    /// Update environment variables in content with new values
    fn update_env_variables(
        &self,
        env_content: &mut String,
        existing_values: &std::collections::HashMap<String, String>,
        config_data: &ConfigUpdateData,
    ) {
        // Helper closure to write environment variable
        let mut write_env_var = |key: &str, new_value: &Option<String>| {
            self.write_env_variable(env_content, existing_values, key, new_value);
        };

        // Write configuration values
        write_env_var(AZURE_AD_TENANT_ID, &config_data.tenant_id);
        write_env_var(AZURE_AD_CLIENT_ID, &config_data.client_id);
        write_env_var(AZURE_AD_SUBSCRIPTION_ID, &config_data.subscription_id);
        write_env_var(AZURE_AD_RESOURCE_GROUP, &config_data.resource_group);
        write_env_var(AZURE_AD_NAMESPACE, &config_data.namespace);

        // Write encrypted credentials from environment
        let encrypted_connection_string =
            std::env::var(SERVICEBUS_ENCRYPTED_CONNECTION_STRING).ok();
        let encryption_salt = std::env::var(SERVICEBUS_ENCRYPTION_SALT).ok();
        let encrypted_client_secret = std::env::var(AZURE_AD_ENCRYPTED_CLIENT_SECRET).ok();
        let client_secret_encryption_salt =
            std::env::var(AZURE_AD_CLIENT_SECRET_ENCRYPTION_SALT).ok();

        write_env_var(
            SERVICEBUS_ENCRYPTED_CONNECTION_STRING,
            &encrypted_connection_string,
        );
        write_env_var(SERVICEBUS_ENCRYPTION_SALT, &encryption_salt);
        write_env_var(AZURE_AD_ENCRYPTED_CLIENT_SECRET, &encrypted_client_secret);
        write_env_var(
            AZURE_AD_CLIENT_SECRET_ENCRYPTION_SALT,
            &client_secret_encryption_salt,
        );

        // Handle queue name based on auth method
        if config_data.auth_method == crate::utils::auth::AUTH_METHOD_CONNECTION_STRING {
            write_env_var(SERVICEBUS_QUEUE_NAME, &config_data.queue_name);
        } else {
            log::debug!("Clearing queue name for non-connection-string auth method");
        }
    }

    /// Write a single environment variable to content
    fn write_env_variable(
        &self,
        env_content: &mut String,
        existing_values: &std::collections::HashMap<String, String>,
        key: &str,
        new_value: &Option<String>,
    ) {
        // Use new value if provided and not empty
        if let Some(value) = new_value {
            if !value.trim().is_empty() {
                Self::append_env_line(env_content, key, value);
                return;
            }
        }

        // Fall back to existing value if available
        if let Some(existing_value) = existing_values.get(key) {
            if !existing_value.trim().is_empty() {
                Self::append_env_line(env_content, key, existing_value);
            }
        }
    }

    /// Append an environment variable line to content with proper formatting
    fn append_env_line(env_content: &mut String, key: &str, value: &str) {
        // Quote connection strings to prevent formatting issues
        if key == SERVICEBUS_ENCRYPTED_CONNECTION_STRING {
            env_content.push_str(&format!("{key}=\"{value}\"\n"));
        } else {
            env_content.push_str(&format!("{key}={value}\n"));
        }
    }

    /// Get the profile-specific .env file path
    fn get_profile_env_path(&self) -> AppResult<String> {
        use crate::config::setup::get_config_dir;

        let config_dir = get_config_dir().map_err(|e| {
            crate::error::AppError::Config(format!("Failed to get config directory: {e}"))
        })?;

        let profile_dir = config_dir.join("profiles").join(DEFAULT_PROFILE_NAME);
        let env_path = profile_dir.join(".env");

        Ok(env_path.to_string_lossy().to_string())
    }

    /// Get the profile-specific config.toml file path
    fn get_profile_config_path(&self) -> AppResult<String> {
        use crate::config::setup::get_config_dir;

        // Always use profile-specific path for consistency
        let config_dir = get_config_dir().map_err(|e| {
            crate::error::AppError::Config(format!("Failed to get config directory: {e}"))
        })?;

        let profile_dir = config_dir.join("profiles").join(DEFAULT_PROFILE_NAME);
        let config_path = profile_dir.join("config.toml");

        Ok(config_path.to_string_lossy().to_string())
    }

    /// Write environment content to file
    fn write_env_content_to_file(&self, env_path: &str, env_content: &str) -> AppResult<()> {
        fs::write(env_path, env_content).map_err(|e| {
            crate::error::AppError::Config(format!("Failed to write .env file: {e}"))
        })?;

        log::info!("Environment variables saved to .env file");
        Ok(())
    }

    fn update_config_toml(&self, config_data: &ConfigUpdateData) -> AppResult<()> {
        // Use profile-based path resolution instead of hardcoded relative path
        let config_path = self.get_profile_config_path()?;

        log::info!(
            "Updating config.toml with auth_method: {}",
            config_data.auth_method
        );

        // Read existing config.toml if it exists
        let mut config_content = if let Ok(content) = fs::read_to_string(&config_path) {
            log::debug!("Read existing config.toml file ({} chars)", content.len());
            content
        } else {
            // Create a basic config.toml structure if it doesn't exist
            log::debug!("Creating new config.toml file");
            String::from("[azure_ad]\n")
        };

        // Update the auth_method in the azure_ad section
        if config_content.contains("[azure_ad]") {
            log::debug!("Found [azure_ad] section in config.toml");
            // Find the azure_ad section and update auth_method
            let lines: Vec<&str> = config_content.lines().collect();
            let mut updated_lines = Vec::new();
            let mut in_azure_ad_section = false;
            let mut auth_method_updated = false;

            for (line_num, line) in lines.iter().enumerate() {
                let trimmed = line.trim();

                if trimmed == "[azure_ad]" {
                    log::debug!("Found [azure_ad] section at line {}", line_num + 1);
                    in_azure_ad_section = true;
                    updated_lines.push(line.to_string());
                } else if trimmed.starts_with('[') && trimmed.ends_with(']') {
                    // Entering a new section
                    if in_azure_ad_section && !auth_method_updated {
                        log::debug!(
                            "Exiting [azure_ad] section at line {}, adding auth_method",
                            line_num + 1
                        );
                        updated_lines
                            .push(format!("auth_method = \"{}\"", config_data.auth_method));
                        auth_method_updated = true;
                    }
                    in_azure_ad_section = false;
                    updated_lines.push(line.to_string());
                } else if in_azure_ad_section && trimmed.starts_with("auth_method") {
                    // Replace existing auth_method line
                    log::debug!(
                        "Found auth_method line at line {}: '{}', replacing with '{}'",
                        line_num + 1,
                        trimmed,
                        config_data.auth_method
                    );
                    updated_lines.push(format!("auth_method = \"{}\"", config_data.auth_method));
                    auth_method_updated = true;
                } else {
                    updated_lines.push(line.to_string());
                }
            }

            // If we didn't find auth_method in azure_ad section, add it
            if in_azure_ad_section && !auth_method_updated {
                log::debug!("No auth_method found in [azure_ad] section, adding it");
                updated_lines.push(format!("auth_method = \"{}\"", config_data.auth_method));
            }

            config_content = updated_lines.join("\n");
            log::debug!("Updated config content ({} chars)", config_content.len());
        } else {
            // Add azure_ad section with auth_method
            log::debug!("No [azure_ad] section found, adding new section");
            config_content.push_str(&format!(
                "\n[azure_ad]\nauth_method = \"{}\"\n",
                config_data.auth_method
            ));
        }

        log::debug!("Writing updated config.toml to disk");
        // Write the updated config.toml
        fs::write(&config_path, config_content).map_err(|e| {
            crate::error::AppError::Config(format!("Failed to write config.toml: {e}"))
        })?;

        log::info!(
            "Configuration saved to config.toml with auth_method: {}",
            config_data.auth_method
        );
        Ok(())
    }

    fn create_auth_service(&mut self) -> AppResult<()> {
        log::info!("Recreating auth service with updated configuration");

        let config = crate::config::get_config_or_panic();
        log::info!(
            "Current auth method from config: '{}'",
            config.azure_ad().auth_method
        );

        // Clear client secret environment variables if not using client_secret auth
        if config.azure_ad().auth_method != "client_secret" {
            log::info!(
                "Clearing client secret environment variables for non-client-secret auth method: {}",
                config.azure_ad().auth_method
            );
            safe_remove_env_var(AZURE_AD_CLIENT_SECRET)?;
        } else {
            log::info!("Keeping client secret environment variables for client_secret auth method");
        }

        // Only create if we're using authentication (not connection_string mode)
        if config.azure_ad().auth_method != "connection_string" {
            log::info!(
                "Creating auth service for method: {}",
                config.azure_ad().auth_method
            );
            let auth_service = std::sync::Arc::new(
                crate::services::AuthService::new(
                    config.azure_ad(),
                    self.state_manager.tx_to_main.clone(),
                    self.http_client.clone(),
                )
                .map_err(|e| crate::error::AppError::Component(e.to_string()))?,
            );

            // Set the global auth state for server components to use
            let auth_state = auth_service.auth_state_manager();
            quetty_server::auth::set_global_auth_state(auth_state.clone());

            // Start the token refresh service with failure callback
            let tx_clone = self.state_manager.tx_to_main.clone();
            tokio::spawn(async move {
                let failure_callback =
                    std::sync::Arc::new(move |error: quetty_server::auth::TokenRefreshError| {
                        log::error!("Token refresh failed: {error}");

                        // Send notification to UI
                        let _ = tx_clone.send(crate::components::common::Msg::AuthActivity(
                            crate::components::common::AuthActivityMsg::TokenRefreshFailed(
                                error.to_string(),
                            ),
                        ));
                    });

                auth_state
                    .start_refresh_service_with_callback(Some(failure_callback))
                    .await;
            });

            // Replace the auth service in the model with the new one
            self.auth_service = Some(auth_service);

            log::info!("Auth service recreated successfully");
        } else {
            // For connection_string mode, clear the auth service
            self.auth_service = None;
            log::info!("Auth service cleared for connection_string mode");
        }

        Ok(())
    }

    fn decrypt_and_set_client_secret(&self, master_password: &str) -> AppResult<()> {
        // Get encrypted client secret and salt from environment
        let encrypted_client_secret =
            std::env::var(AZURE_AD_ENCRYPTED_CLIENT_SECRET).map_err(|_| {
                crate::error::AppError::Config(
                    format!("{AZURE_AD_ENCRYPTED_CLIENT_SECRET} environment variable not found")
                        .to_string(),
                )
            })?;

        let encryption_salt =
            std::env::var(AZURE_AD_CLIENT_SECRET_ENCRYPTION_SALT).map_err(|_| {
                crate::error::AppError::Config(
                    format!(
                        "{AZURE_AD_CLIENT_SECRET_ENCRYPTION_SALT} environment variable not found"
                    )
                    .to_string(),
                )
            })?;

        // Create encryption instance with the salt
        let encryption =
            ClientSecretEncryption::from_salt_base64(&encryption_salt).map_err(|e| {
                crate::error::AppError::Config(format!(
                    "Failed to initialize client secret encryption: {e}"
                ))
            })?;

        // Decrypt the client secret
        let decrypted_client_secret = encryption
            .decrypt_client_secret(&encrypted_client_secret, master_password)
            .map_err(|e| {
                crate::error::AppError::Config(format!("Failed to decrypt client secret: {e}"))
            })?;

        // Set the decrypted client secret as environment variable for runtime use
        safe_set_env_var(AZURE_AD_CLIENT_SECRET, &decrypted_client_secret)?;

        // Log first few characters for verification (security safe)
        let preview = if decrypted_client_secret.len() > 6 {
            format!("{}***", &decrypted_client_secret[..6])
        } else {
            "***".to_string()
        };
        log::info!(
            "Client secret successfully decrypted and set for runtime use (preview: {preview})"
        );
        Ok(())
    }
}