//
//  AdRevenueTracker.swift
//  PhoneManager
//
//  Created by edy on 2025/6/18.
//

import Foundation
import Foundation
import FirebaseAnalytics
import GoogleMobileAds
import StoreKit
import AdjustSdk

class AdRevenueTracker {
    private let taichiPref = UserDefaults.standard
    
    func onPaidEvent(adValue: AdValue) {
        // 记录广告收入事件
        var params = [String: Any]()
        let currentImpressionRevenue = adValue.value.floatValue
        params[AnalyticsParameterValue] = currentImpressionRevenue
        params[AnalyticsParameterCurrency] = "USD"
        
        // 记录精度类型
        let precisionType: String
        switch adValue.precision.rawValue {
        case 0: precisionType = "UNKNOWN"
        case 1: precisionType = "ESTIMATED"
        case 2: precisionType = "PUBLISHER_PROVIDED"
        case 3: precisionType = "PRECISE"
        default: precisionType = "Invalid"
        }
        params["precisionType"] = precisionType
        
        // 记录广告收入事件
        Analytics.logEvent("Ad_Impression_Revenue", parameters: params)
        
        // 获取并更新本地累计值
        let previousTaichiTroasCache = taichiPref.float(forKey: "TaichiTroasCache")
        let currentTaichiTroasCache = previousTaichiTroasCache + currentImpressionRevenue
        
        // 检查是否需要发送tROAS事件
        if currentTaichiTroasCache >= 0.01 {
            // 发送tROAS事件并重置缓存
            var roasbundle = [String: Any]()
            roasbundle[AnalyticsParameterValue] = Double(currentTaichiTroasCache)
            roasbundle[AnalyticsParameterCurrency] = "USD"
            Analytics.logEvent("Total_Ads_Revenue_001", parameters: roasbundle)
            Analytics.logEvent("hybrid_revenue", parameters: roasbundle)
            taichiPref.set(0.0, forKey: "TaichiTroasCache")
        } else {
            // 继续累积收入
            taichiPref.set(currentTaichiTroasCache, forKey: "TaichiTroasCache")
        }
        
        // 同步保存设置（Swift的UserDefaults自动异步保存，无需显式调用）
        taichiPref.synchronize() // 注意：iOS 12+后通常不需要调用此方法
    }
    
    // 上报数据
    func purchasingSuccessReport(type:SubscriptionType){
        
        guard let prod = IAPManager.share.getSKProductBy(type) else{
            return
        }

        // firebase上报
        let pram = [
            AnalyticsParameterValue:prod.price.floatValue,
            AnalyticsParameterCurrency:prod.priceLocale.currencyCode ?? "USD"
        ] as [String : Any]
        Analytics.logEvent("hybrid_revenue", parameters: pram)
        
        // adjust上报
        guard let event = ADJEvent(eventToken: "tj07yb") else { return }
        event.setRevenue(prod.price.doubleValue, currency: prod.priceLocale.currencyCode ?? "USD")
        Adjust.trackEvent(event)
    }
}

