import Foundation

final class NotificationSender: ObservableObject {

    @Published
    var isTransmittingToRemote = false

    @Published
    var lastPushWasSuccessful = true

    init() {

    }

    func failedToCreateNotificationDueToMissingSettings() {
        guard !isTransmittingToRemote else { return }
        DispatchQueue.main.async {
            self.lastPushWasSuccessful = false
        }
    }

    func send(url: String, request: NotificationRequest) {
        guard !isTransmittingToRemote else { return }
        DispatchQueue.main.async {
            self.isTransmittingToRemote = true
        }
        
        guard let url = URL(string: url) else {
            print("Invalid notification url: \(url)")
            didFinish(success: false)
            return
        }
        let body: Data
        do {
            body = try JSONEncoder().encode(request)
        } catch {
            print("Failed to encode notification: \(error)")
            didFinish(success: false)
            return
        }
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.httpBody = body

        Task {
            do {
                let (_ , result) = try await URLSession.shared.data(for: request)
                guard let response = result as? HTTPURLResponse else {
                    print("Invalid response \(result)")
                    didFinish(success: false)
                    return
                }
                guard response.statusCode == 200 else {
                    print("Failed to send notification: \(response.statusCode)")
                    didFinish(success: false)
                    return
                }
                didFinish(success: true)
            } catch {
                print("Failed to send notification request: \(error)")
                didFinish(success: false)
                return
            }
        }
    }

    private func didFinish(success: Bool) {
        DispatchQueue.main.async {
            self.isTransmittingToRemote = false
            self.lastPushWasSuccessful = success
        }
    }
}
