import Foundation

@MainActor
final class AuthViewModel: ObservableObject {
    enum Phase { case phone, otp }

    private let repo: AuthRepository

    @Published var phase: Phase = .phone
    @Published var phone = ""
    @Published var code = ""
    @Published private(set) var loading = false
    @Published private(set) var error: String?

    init(repo: AuthRepository) {
        self.repo = repo
    }

    func requestCode() {
        let value = phone.trimmingCharacters(in: .whitespaces)
        guard !value.isEmpty else { return }
        run {
            try await self.repo.requestCode(phone: value)
            self.phase = .otp
        }
    }

    func verify() {
        let value = code.trimmingCharacters(in: .whitespaces)
        guard !value.isEmpty else { return }
        run {
            // On success the session flips → RootView navigates to the main app.
            try await self.repo.verify(phone: self.phone.trimmingCharacters(in: .whitespaces), code: value)
        }
    }

    func back() {
        phase = .phone
        code = ""
        error = nil
    }

    private func run(_ operation: @escaping () async throws -> Void) {
        loading = true
        error = nil
        Task {
            do {
                try await operation()
            } catch let err {
                error = (err as? LocalizedError)?.errorDescription ?? err.localizedDescription
            }
            loading = false
        }
    }
}
