import Network
import Foundation
import Observation

@Observable
@MainActor
final class ConnectivityMonitor {
    static let shared = ConnectivityMonitor()

    private(set) var isConnected: Bool = true

    private let monitor = NWPathMonitor()
    private let queue = DispatchQueue(label: "com.bookstax.connectivity", qos: .utility)

    private init() {
        monitor.pathUpdateHandler = { [weak self] path in
            let connected = path.status == .satisfied
            Task { @MainActor [weak self] in
                guard let self else { return }
                if self.isConnected != connected {
                    AppLog(connected ? .info : .warning,
                           connected ? "Network connection restored" : "Network connection lost",
                           category: "Network")
                }
                self.isConnected = connected
            }
        }
        monitor.start(queue: queue)
    }

    deinit {
        monitor.cancel()
    }
}
