import Combine
import Foundation
import Network

protocol NetworkStatusProviding: AnyObject {
    var isOnline: Bool { get }
    func startMonitoring()
    func stopMonitoring()
}

@MainActor
final class NetworkMonitor: ObservableObject, NetworkStatusProviding {
    @Published private(set) var isOnline = true

    private let monitor = NWPathMonitor()
    private let queue = DispatchQueue(label: "StackDex.NetworkMonitor")
    private var isMonitoring = false

    func startMonitoring() {
        guard !isMonitoring else { return }
        isMonitoring = true

        monitor.pathUpdateHandler = { [weak self] path in
            let isSatisfied = path.status == .satisfied
            DispatchQueue.main.async {
                self?.isOnline = isSatisfied
            }
        }
        monitor.start(queue: queue)
    }

    func stopMonitoring() {
        guard isMonitoring else { return }
        monitor.cancel()
        isMonitoring = false
    }
}
