//
//  UmengBootstrap.swift
//  suixinkan
//

import Foundation

/// 友盟 SDK 隐私合规初始化入口，必须在用户同意隐私政策后调用。
enum UmengBootstrap {

    /// 当前进程内是否已经完成友盟 SDK 初始化。
    private(set) static var isConfigured = false

    private static let lock = NSLock()
    private static var configureHandler: (_ appKey: String, _ channel: String) -> Void = { appKey, channel in
        UMConfigure.setLogEnabled(false)
        UMConfigure.initWithAppkey(appKey, channel: channel)
    }

    /// 在用户已同意 App 隐私政策后配置友盟 SDK，幂等。
    @discardableResult
    static func configureIfNeeded(appStore: AppStore = .shared) -> Bool {
        guard appStore.session.privacyAgreementAccepted else { return false }

        lock.lock()
        defer { lock.unlock() }
        guard !isConfigured else { return true }

        configureHandler(UmengConfig.appKey, UmengConfig.channel)
        isConfigured = true
        return true
    }

    /// 测试专用：替换真实 SDK 初始化实现。
    static func setConfigureHandlerForTesting(_ handler: @escaping (_ appKey: String, _ channel: String) -> Void) {
        lock.lock()
        defer { lock.unlock() }
        configureHandler = handler
    }

    /// 测试专用：重置初始化状态与默认初始化实现。
    static func resetForTesting() {
        lock.lock()
        defer { lock.unlock() }
        isConfigured = false
        configureHandler = { appKey, channel in
            UMConfigure.setLogEnabled(false)
            UMConfigure.initWithAppkey(appKey, channel: channel)
        }
    }
}
