AutoCat/AutoCat/Screens/AuthScreen/AuthViewModel.swift

73 lines
1.8 KiB
Swift

//
// AuthViewModel.swift
// AutoCat
//
// Created by Selim Mustafaev on 05.04.2025.
// Copyright © 2025 Selim Mustafaev. All rights reserved.
//
import SwiftUI
import AutoCatCore
@MainActor
@Observable
final class AuthViewModel: ACHudContainer {
let apiService: ApiServiceProtocol
let storageService: StorageServiceProtocol
var settingsService: SettingsServiceProtocol
var coordinator: AuthCoordinator?
var hud: ACHud?
var email: String = ""
var password: String = ""
var actionsEnabled: Bool {
email.count >= 5 && password.count >= 5
}
init(
apiService: ApiServiceProtocol,
storageService: StorageServiceProtocol,
settingsService: SettingsServiceProtocol
) {
self.apiService = apiService
self.storageService = storageService
self.settingsService = settingsService
}
func onAppear() {
if settingsService.user.email.count > 0 {
email = settingsService.user.email
}
}
func login() async {
await wrapWithToast { [weak self] in
guard let self else { return }
let user = try await apiService.login(email: email, password: password)
try await saveUser(user)
coordinator?.openMainScreen()
}
}
func signup() async {
await wrapWithToast { [weak self] in
guard let self else { return }
let user = try await apiService.signUp(email: email, password: password)
try await saveUser(user)
coordinator?.openMainScreen()
}
}
func saveUser(_ user: User) async throws {
if user.email != settingsService.user.email {
try await storageService.deleteAll()
}
settingsService.user = user
}
}