//
//  QSAppleAdHandle.swift
//  QuickSearchLocation
//
//  Created by Destiny on 2025/7/17.
//

import Foundation
import AdServices
import AdSupport


class QSAppleAdHandle {
    
    var retryRequestCount = 0
    
    static func initQSC() {
        
        if #available(iOS 14.3, *) {
            do {
                let appleAttributionToken = try AAAttribution.attributionToken()
                // 尝试获取归因信息
                QSAppleAdHandle().getQSC(token: appleAttributionToken)
            } catch let error {
                print("Error fetching attribution token: \(error.localizedDescription)")
            }
        }
    }
    
    // 开始获取归因结果
    private func getQSC(token: String) {
        
        guard retryRequestCount < 3 else { return }
        
        let configuration = URLSessionConfiguration.default
        let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: nil)
        let asaUrl = URL(string: "https://api-adservices.apple.com/api/v1/")!
        
        var request = URLRequest(url: asaUrl)
        request.httpMethod = "POST"
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpBody = token.data(using: .utf8)
        
        let task = session.dataTask(with: request) { data, response, error in
            if let error = error {
                print("sendASAToken error = \(error)")
                // 5秒后重试
                DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
                    self.getQSC(token: token)
                }
                return
            }
            
            guard let data = data, let payloadDic = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else {
                print("sendASAToken error payload = nil")
                // 5秒后重试
                DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
                    self.getQSC(token: token)
                }
                return
            }
            
            print("sendASAToken payload = \(payloadDic)")
            
            if let attributionObj = payloadDic["attribution"] {
                UserDefaults.standard.set(payloadDic, forKey: "QS_ATTRIBUTION_PAYLOAD")
                UserDefaults.standard.synchronize()
                
                ///调用奇异果数据上报接口
                let wikiManager = QSWikiHandle.shared
                
                wikiManager.addAttributionResultReport { isSuccess in
                    print("asaReportWithCompletion = ", isSuccess)
    
                    if isSuccess {
                        let isRegister = UserDefaults.standard.bool(forKey: "areHaveRegisterKey")
                        if !isRegister {
                            QSWikiHandle.shared.addEventResultAttribution(eventDict: ["event_name": "active", "event_val": 1])
                            QSWikiHandle.shared.addEventResultAttribution(eventDict: ["event_name": "register", "event_val": 1])
                            UserDefaults.standard.setValue(true, forKey: "areHaveRegisterKey")
                        }
                    }
                }
            }
        }
        task.resume()
        retryRequestCount += 1
    }
}
