//
//  AMapBootstrap.swift
//  suixinkan
//

import Foundation

/// 高德 SDK 隐私合规与 Key 初始化，必须在实例化任何 SDK 类之前完成。
enum AMapBootstrap {

    private(set) static var isConfigured = false
    private static let lock = NSLock()

    /// 在用户已同意 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 }

        #if !targetEnvironment(simulator)
        AMapLocationManager.updatePrivacyShow(.didShow, privacyInfo: .didContain)
        AMapLocationManager.updatePrivacyAgree(.didAgree)
        MAMapView.updatePrivacyShow(.didShow, privacyInfo: .didContain)
        MAMapView.updatePrivacyAgree(.didAgree)
        AMapSearchAPI.updatePrivacyShow(.didShow, privacyInfo: .didContain)
        AMapSearchAPI.updatePrivacyAgree(.didAgree)

        AMapServices.shared().apiKey = AMapConfig.apiKey
        AMapServices.shared().enableHTTPS = true
        #endif
        isConfigured = true
        return true
    }

    /// 要求高德 SDK 已完成合规初始化，否则抛出错误。
    static func requireConfigured(appStore: AppStore = .shared) throws {
        guard configureIfNeeded(appStore: appStore) else {
            throw LocationProviderError.privacyNotAccepted
        }
    }

    /// 测试专用：重置初始化状态。
    static func resetForTesting() {
        lock.lock()
        defer { lock.unlock() }
        isConfigured = false
    }
}
