//
//  PushManager.swift

//
//  Created by Leon on 2025/7/12.
//

import Foundation
import UIKit

class PushManager: NSObject {
    public static let shared = PushManager()
    var toSubmitPushToken: String = ""

    override required init() {
        super.init()
        NotificationCenter.default.addObserver(self, selector: #selector(notiLoginSuccess), name: AppNotificationName.userLoginSuccess.notificationName, object: nil)
        UNUserNotificationCenter.current().delegate = self
    }

    deinit {
        NotificationCenter.default.removeObserver(self)
    }

    static func trySubmmitPushTokenFromNewGet(token: String) {
        guard let userId = UserCore.shared.user?.userId else {
            PushManager.shared.toSubmitPushToken = token
            return
        }

        // ...
    }

    static func registerNotiPush(application: UIApplication) {
        let center = UNUserNotificationCenter.current()
        center.delegate = PushManager.shared
        center.getNotificationSettings { setting in
            if setting.authorizationStatus == .notDetermined {
                center.requestAuthorization(options: [.badge, .sound, .alert]) { result, error in
                    if result {
                        if !(error != nil) {
                            // 注册成功
                            DispatchQueue.main.async {
                                application.registerForRemoteNotifications()
                            }
                        }
                    } else {
                        // 用户不允许推送
                    }
                }
            } else if setting.authorizationStatus == .denied {
                // 申请用户权限被拒
            } else if setting.authorizationStatus == .authorized {
                // 用户已授权（再次获取dt）
                DispatchQueue.main.async {
                    application.registerForRemoteNotifications()
                }
            } else {
                // 未知错误
            }
        }
    }

    // MARK: - noti

    @objc private func notiLoginSuccess() {
        if toSubmitPushToken.count > 0 {
            PushManager.trySubmmitPushTokenFromNewGet(token: toSubmitPushToken)
        }
    }

    // MARK: - helper

    private func dealPushNotification(userInfo: [AnyHashable: Any]?) {
    }

    private func dealLocalNotification(userInfo: [AnyHashable: Any]?) {
        // none.
    }
}

extension PushManager: UNUserNotificationCenterDelegate {
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        let dict = notification.request.content.userInfo
        dlog("☁️前台收到推送：\(dict) ")
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        let dict = response.notification.request.content.userInfo
        dlog("☁️后台收到推送：\(dict) ")

        // UserCore.shared.refreshUserInfo(block: nil)

        if let trigger = response.notification.request.trigger {
            if trigger is UNPushNotificationTrigger {
                dealPushNotification(userInfo: dict)
            } else if trigger is UNTimeIntervalNotificationTrigger {
                dealLocalNotification(userInfo: dict)
            }
        }

        completionHandler()
    }
}
