import Foundation
import Network
import Observation

/// Tracks whether background maintenance/cloud sync is running and whether the
/// device has network connectivity. The sync toast is visible only when both
/// are true.
@MainActor
@Observable
final class SyncStatusMonitor {
    private(set) var isSyncing = false
    private(set) var isNetworkAvailable = true

    private let pathMonitor = NWPathMonitor()
    private let monitorQueue = DispatchQueue(label: "com.conjuga.app.sync-monitor")

    init() {
        pathMonitor.pathUpdateHandler = { [weak self] path in
            let available = (path.status == .satisfied)
            Task { @MainActor in
                self?.isNetworkAvailable = available
            }
        }
        pathMonitor.start(queue: monitorQueue)
    }

    deinit {
        pathMonitor.cancel()
    }

    var shouldShowToast: Bool {
        isSyncing && isNetworkAvailable
    }

    func beginSync() {
        isSyncing = true
    }

    func endSync() {
        isSyncing = false
    }
}
