import Foundation
import Observation

@MainActor
@Observable
final class OLTDetailViewModel {
    let oltId: String
    private let connection: MCMSConnection

    var phase: LoadPhase = .idle
    var olt: OLTStateDoc?

    var isPerformingAction = false
    var actionMessage: String?

    init(connection: MCMSConnection, oltId: String) {
        self.connection = connection
        self.oltId = oltId
    }

    func load() async {
        phase = .loading
        do {
            olt = try await connection.olt.state(id: oltId)
            phase = .loaded
        } catch {
            phase = .failed((error as? APIError)?.localizedDescription ?? error.localizedDescription)
        }
    }

    func reset() async {
        isPerformingAction = true
        actionMessage = nil
        do {
            try await connection.olt.reset(id: oltId)
            actionMessage = "Reset requested."
        } catch {
            actionMessage = (error as? APIError)?.localizedDescription ?? error.localizedDescription
        }
        isPerformingAction = false
    }
}
