//
//  NetworkMonitor.swift
//  B24PaymentSdk
//
//  Created by Hout 14/01/26
//

import Foundation
import Network

public class NetworkMonitor {
    public static let shared = NetworkMonitor()
    
    private var monitor: NWPathMonitor?
    private let queue = DispatchQueue(label: "NetworkMonitor")
    
    public private(set) var isConnected: Bool = true
    private(set) var connectionType: NWInterface.InterfaceType?
    
    public var onConnectionStatusChanged: ((Bool) -> Void)?
    
    private init() {}
    
    public func startMonitoring() {
        // Stop any existing monitor before starting a new one
        stopMonitoring()
        
        let newMonitor = NWPathMonitor()
        newMonitor.pathUpdateHandler = { [weak self] path in
            guard let self = self else { return }
            
            let wasConnected = self.isConnected
            self.isConnected = path.status == .satisfied
            self.connectionType = path.availableInterfaces.first?.type
            
            // Notify on main thread when connection status changes
            if wasConnected != self.isConnected {
                DispatchQueue.main.async {
                    self.onConnectionStatusChanged?(self.isConnected)
                }
            }
        }
        
        self.monitor = newMonitor
        newMonitor.start(queue: queue)
    }
    
    public func stopMonitoring() {
        monitor?.cancel()
        monitor = nil
    }
}
