using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; using UtopiaCanteenSystem.Services; namespace UtopiaCanteenSystem.ViewModels; public partial class AdminSettingsAuthViewModel : ObservableObject { private readonly IAuthService _authService; private readonly AppSession _session; private readonly INavigationService _navigation; private readonly IConfigService _config; private readonly IEmployeeLookupService _employeeLookup; [ObservableProperty] private string _username = string.Empty; // Updated from code-behind (PasswordBox doesn't support binding cleanly). [ObservableProperty] private string _password = string.Empty; [ObservableProperty] private string _errorMessage = string.Empty; [ObservableProperty] private bool _isBusy; [ObservableProperty] private bool _rememberCredentials; public AdminSettingsAuthViewModel( IAuthService authService, AppSession session, INavigationService navigation, IConfigService config, IEmployeeLookupService employeeLookup) { _authService = authService; _session = session; _navigation = navigation; _config = config; _employeeLookup = employeeLookup; RememberCredentials = _config.GetRememberAdminCredentials(); if (RememberCredentials) { Username = _config.GetSavedAdminUsername(); Password = _config.GetSavedAdminPassword(); } } [RelayCommand] private void Cancel() { _navigation.NavigateToScanner(); } [RelayCommand] private async Task ConfirmAsync() { if (IsBusy) return; ErrorMessage = string.Empty; var user = Username?.Trim() ?? string.Empty; var pass = Password ?? string.Empty; // Requirement: always clear fields after clicking Confirm (success or failure). // Keep local copies for the ongoing request. Username = string.Empty; Password = string.Empty; if (string.IsNullOrWhiteSpace(user) || string.IsNullOrEmpty(pass)) { ErrorMessage = "Admin username and password are required."; return; } IsBusy = true; try { var result = await _authService.LoginAsync(user, pass).ConfigureAwait(true); if (!result.Success) { ErrorMessage = "Admin rights required. Invalid username/password."; return; } // Refresh session details (who authenticated for Settings). _session.SetAdminAuthenticated(user, result.EmployeeId); try { var siteId = await _employeeLookup.GetLocationSiteIdByEmployeeSerialAsync(result.EmployeeId).ConfigureAwait(true); _config.ApplyLocationSiteIdFromAuth(siteId); } catch { // HRMS lookup optional; auth still succeeds. } // Persist credentials only if user opted in. _config.SetRememberAdminCredentials(RememberCredentials); if (RememberCredentials) { _config.SetSavedAdminUsername(user); _config.SetSavedAdminPassword(pass); } else { _config.SetSavedAdminUsername(string.Empty); _config.SetSavedAdminPassword(string.Empty); } _navigation.NavigateToSettings(); } finally { IsBusy = false; } } }