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?

    /// Bumped on every load; a load only commits if it's still the latest, so a
    /// stale/overlapping request (pull-to-refresh racing the .task) can't clobber
    /// newer results.
    private var loadGeneration = 0

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

    func load() async {
        loadGeneration += 1
        let gen = loadGeneration
        phase = .loading
        do {
            let fetched = try await connection.olt.state(id: oltId)
            guard gen == loadGeneration, !Task.isCancelled else { return }
            olt = fetched
            phase = .loaded
        } catch {
            guard gen == loadGeneration, !Task.isCancelled else { return }
            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
    }
}
