//
//  QSLInAppReviewmanager.swift
//  QuickSearchLocation
//
//  Created by Destiny on 2025/7/30.
//

import StoreKit

class QSLInAppReviewmanager {
    // 记录应用启动次数
    static let launchCountKey = "AppLaunchCount"
    
    // 检查并请求评论
    static func requestReviewIfAppropriate() {
        // 获取应用启动次数
        let defaults = UserDefaults.standard
        var launchCount = defaults.integer(forKey: launchCountKey)
        launchCount += 1
        defaults.set(launchCount, forKey: launchCountKey)
        
        // 在适当的时机请求评论（例如第5次、第20次启动等）
        if launchCount == 5 || launchCount == 20 || launchCount == 50 {
            requestReview()
        }
    }
    
    // 直接请求评论（需要满足App Store的条件才会显示）
    static func requestReview() {
        if #available(iOS 14.0, *) {
            // 获取当前窗口场景
            if let windowScene = UIApplication.shared.connectedScenes
                .first(where: { $0.activationState == .foregroundActive }) as? UIWindowScene {
                SKStoreReviewController.requestReview(in: windowScene)
            }
        } else {
            // iOS 14以下版本
            SKStoreReviewController.requestReview()
        }
    }
    
    // 引导用户到App Store评论页面（备用方案）
    static func openAppStoreReviewPage() {
        guard let appId = Bundle.main.object(forInfoDictionaryKey: "CFBundleIdentifier") as? String else { return }
        let urlString = "itms-apps://itunes.apple.com/app/id\(appId)?action=write-review"
        
        if let url = URL(string: urlString), UIApplication.shared.canOpenURL(url) {
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
        }
    }
}
/*
// 使用示例
// 在应用启动时调用（通常在AppDelegate或SceneDelegate中）
func applicationDidBecomeActive(_ application: UIApplication) {
    InAppReviewManager.requestReviewIfAppropriate()
}

// 或者在用户完成关键操作后调用
func userCompletedSignificantAction() {
    InAppReviewManager.requestReview()
}

// 作为备用方案，在用户拒绝原生弹窗后引导到App Store
func showAppStoreReviewPage() {
    InAppReviewManager.openAppStoreReviewPage()
}
*/
