//
//  SDLTunnelAppNotifier.swift
//  Tun
//
//  Created by 安礼成 on 2026/4/15.
//

import Foundation

final class SDLTunnelAppNotifier {
    static let shared = SDLTunnelAppNotifier()
    
    private let suiteName: String
    private let eventKey: String
    
    init(suiteName: String = SDLNotificationCenter.Configuration.appGroupSuiteName,
         eventKey: String = SDLNotificationCenter.Configuration.latestEventKey) {
        self.suiteName = suiteName
        self.eventKey = eventKey
    }
    
    func publish(code: Int? = nil, message: String) {
        var event = TunnelEvent()
        event.id = UUID().uuidString
        event.timestampMs = UInt64(Date().timeIntervalSince1970 * 1000)
        event.code = Int32(clamping: code ?? 0)
        event.message = message
        self.publish(event)
    }
    
    func publish(_ event: TunnelEvent) {
        guard let shared = UserDefaults(suiteName: self.suiteName),
              let data = try? event.serializedData() else {
            return
        }
        
        shared.set(data, forKey: self.eventKey)
        shared.synchronize()
        SDLNotificationCenter.shared.post(.tunnelEventChanged)
    }
    
    func clear() {
        guard let shared = UserDefaults(suiteName: self.suiteName) else {
            return
        }
        
        shared.removeObject(forKey: self.eventKey)
        shared.synchronize()
        SDLNotificationCenter.shared.post(.tunnelEventChanged)
    }
}
