//
//  idfa.swift
//  playbtest
//
//  Created by 忆海16 on 2024/12/31.
//

import AdSupport
import AppTrackingTransparency
import Foundation

class IDFA {
    static let shared = IDFA()

    /// 检查并请求 ATT 授权
    @available(iOS 14, *)
    func checkATT(completion: @escaping (String?) -> Void) {
        let status = ATTrackingManager.trackingAuthorizationStatus
        switch status {
        case .notDetermined:
            // 请求授权
            ATTrackingManager.requestTrackingAuthorization { newStatus in
                self.handleATTStatus(newStatus, completion: completion)
            }
        case .authorized, .denied, .restricted:
            // 处理已有的状态
            handleATTStatus(status, completion: completion)
        @unknown default:
            completion(nil)
        }
    }

    /// 处理 ATT 授权状态
    @available(iOS 14, *)
    private func handleATTStatus(
        _ status: ATTrackingManager.AuthorizationStatus,
        completion: @escaping (String?) -> Void
    ) {
        switch status {
        case .authorized:
            // 用户已授权，获取 IDFA
            let idfa = ASIdentifierManager.shared().advertisingIdentifier
                .uuidString
            completion(idfa)
        //            starManager.shared.idfa = idfa
        case .denied, .restricted:
            // 用户拒绝或受限，返回 nil
            print("用户拒绝授权或功能受限")
            completion(nil)
        case .notDetermined:
            // 不应该出现，预防性处理
            print("授权状态仍未确定")
            completion(nil)
        @unknown default:
            completion(nil)
        }
    }

    func getIDFAForOlderVersions(completion: @escaping (String?) -> Void) {
        if ASIdentifierManager.shared().isAdvertisingTrackingEnabled {
            let idfa = ASIdentifierManager.shared().advertisingIdentifier
                .uuidString
            completion(idfa)
        } else {
            print("广告跟踪受限")
            completion(nil)
        }
    }
}

//func requestIDFA(completion: @escaping (String?) -> Void) {
//    if #available(iOS 14.5, *) {
//        // 检查跟踪授权状态
//        ATTrackingManager.requestTrackingAuthorization { status in
//            switch status {
//            case .authorized:
//                // 用户授权后，获取 IDFA
//                let idfa = ASIdentifierManager.shared().advertisingIdentifier.uuidString
//                completion(idfa)
//            case .denied, .restricted, .notDetermined:
//                // 用户拒绝、限制或未决定时，IDFA 将不可用
//                completion(nil)
//            @unknown default:
//                completion(nil)
//            }
//        }
//    } else {
//        // 对于 iOS 14.4 及以下版本，直接获取 IDFA
//        if ASIdentifierManager.shared().isAdvertisingTrackingEnabled {
//            let idfa = ASIdentifierManager.shared().advertisingIdentifier.uuidString
//            completion(idfa)
//        } else {
//            completion(nil)
//        }
//    }
//}
