import Combine import Foundation @MainActor final class AuthSessionStore: ObservableObject { enum State { case checking case signedOut case signedIn } @Published private(set) var state: State = .checking @Published private(set) var isSigningIn = false static let shared = AuthSessionStore() private let api = MusicAPI() init(initialState: State = .checking) { state = initialState debug("store initialized; state=\(stateName(state))") } func restoreSession() async { debug("restore requested; state=\(stateName(state))") guard state == .checking else { return } do { let authenticated = try await api.sessionStatus().authenticated guard !Task.isCancelled else { debug("session restore cancelled; leaving state unchanged") return } state = authenticated ? .signedIn : .signedOut debug("session restore completed; authenticated=\(authenticated)") } catch is CancellationError { debug("session restore cancelled; leaving state unchanged") } catch { guard !Task.isCancelled else { debug("session restore cancelled after request error; leaving state unchanged") return } debug("session restore failed: \(error.localizedDescription)") state = .signedOut } } func signIn(email: String, password: String) async throws { isSigningIn = true defer { isSigningIn = false } try await api.signIn(email: email, password: password) state = .signedIn } private func debug(_ message: String) { #if DEBUG print("[AuthSessionStore] pid=\(ProcessInfo.processInfo.processIdentifier) \(message)") #endif } private func stateName(_ state: State) -> String { switch state { case .checking: "checking" case .signedOut: "signedOut" case .signedIn: "signedIn" } } }