namespace NetinaShop.AdminPanel.PWA.Pages;

public class LoginPageViewModel : BaseViewModel
{
    private readonly IRestWrapper _restWrapper;
    private readonly NavigationManager _navigationManager;
    private readonly IUserUtility _userUtility;
    private readonly ISnackbar _snackbar;
    public LoginPageViewModel(ISnackbar snackbar, IRestWrapper restWrapper,NavigationManager navigationManager,IUserUtility userUtility)
    {
        _snackbar = snackbar;
        _restWrapper = restWrapper;
        _navigationManager = navigationManager;
        _userUtility = userUtility;
    }
    public bool PhoneNumberConfirmed { get; set; }
    public string PhoneNumber { get; set; } = string.Empty;
    public string VerifyCode { get; set; } = string.Empty;
    public async Task SubmitAsync()
    {
        try
        {
            IsProcessing = true;
            if (!PhoneNumberConfirmed)
            {
                await _restWrapper.AuthRestApi.GetVerifyCodeAsync(PhoneNumber);
                PhoneNumberConfirmed = true;
            }
            else
            {
                var dto = await _restWrapper.AuthRestApi.LoginWithVerifyCodeAsync(new LoginRequestDto
                    { UserName = PhoneNumber, VerifyCode = VerifyCode });
                await _userUtility.SetUserAsync(dto.User);
                await _userUtility.SetPermissionsAsync(dto.Permissions);
                await _userUtility.SetBearerTokenAsync(dto.BearerToken);
                _navigationManager.NavigateTo("home",true,true);
            }
        }
        catch (ApiException ex)
        {
            var exe = await ex.GetContentAsAsync<ApiResult>();
            _snackbar.Add(exe != null ? exe.Message : ex.Content, Severity.Error);
        }
        catch (Exception e)
        {
            _snackbar.Add(e.Message, Severity.Error);
        }
        finally
        {

            IsProcessing = false;
        }
    }
}