/**
 * SaaS授权系统 - Swift/iOS客户端
 *
 * 使用说明：
 * 1. 修改 API_KEY 为您的真实API密钥
 * 2. 将此文件导入到您的Xcode项目中
 * 3. 调用验证：AuthorizationClient.verify(authCode: "AUTH_CODE") { result in ... }
 *
 * 要求：iOS 13.0+ / macOS 10.15+ / Swift 5.5+
 *
 * @author 授权系统
 * @version 1.0.0
 */

import Foundation

// ==================== 授权客户端 ====================

/// SaaS授权验证客户端
public class AuthorizationClient {
    
    // MARK: - 配置
    
    /// API密钥（从开发者中心获取）
    /// 网址：https://kuio.cn/user/developer
    public var apiKey: String = "your_api_key_here"
    
    /// API接口地址
    public var baseURL: String = "https://kuio.cn/api/saas"
    
    /// 是否启用缓存
    public var cacheEnabled: Bool = true
    
    /// 缓存时长（秒），默认30分钟
    public var cacheDuration: TimeInterval = 1800
    
    // MARK: - 缓存
    private var cache: [String: CacheItem] = [:]
    
    // MARK: - URLSession
    private let session: URLSession = {
        let config = URLSessionConfiguration.default
        config.timeoutIntervalForRequest = 10
        config.timeoutIntervalForResource = 30
        return URLSession(configuration: config)
    }()
    
    // MARK: - 单例（可选）
    public static let shared = AuthorizationClient()
    
    // MARK: - 初始化
    public init(apiKey: String = "your_api_key_here") {
        self.apiKey = apiKey
    }
    
    // MARK: - 核心方法
    
    /// 验证授权（带缓存）
    ///
    /// - Parameters:
    ///   - authCode: 授权码
    ///   - domain: 域名（可选）
    ///   - ip: IP地址（可选）
    ///   - completion: 回调结果
    public func verify(
        authCode: String,
        domain: String? = nil,
        ip: String? = nil,
        completion: @escaping (AuthResult) -> Void
    ) {
        // 1. 尝试从缓存读取
        if cacheEnabled, let cached = cache[authCode] {
            if Date().timeIntervalSince(cached.timestamp) < cacheDuration {
                completion(AuthResult(
                    success: true,
                    message: "授权验证成功（缓存）",
                    data: cached.data,
                    fromCache: true
                ))
                return
            }
            cache.removeValue(forKey: authCode)
        }
        
        // 2. 调用API验证
        verifyFromApi(authCode: authCode, domain: domain, ip: ip) { [weak self] result in
            guard let self = self else { return }
            
            // 3. 成功则写入缓存
            if result.success && self.cacheEnabled {
                self.cache[authCode] = CacheItem(data: result.data, timestamp: Date())
            }
            
            completion(result)
        }
    }
    
    /// 验证授权（async/await 版本，需要 iOS 15+ / macOS 12+）
    @available(iOS 15.0, macOS 12.0, *)
    public func verify(authCode: String, domain: String? = nil, ip: String? = nil) async throws -> AuthResult {
        try await withCheckedThrowingContinuation { continuation in
            verify(authCode: authCode, domain: domain, ip: ip) { result in
                continuation.resume(returning: result)
            }
        }
    }
    
    // MARK: - 私有方法
    
    private func verifyFromApi(
        authCode: String,
        domain: String?,
        ip: String?,
        completion: @escaping (AuthResult) -> Void
    ) {
        let url = URL(string: "\(baseURL)/verify")!
        
        var body: [String: String] = ["authcode": authCode]
        if let domain = domain, !domain.isEmpty { body["domain"] = domain }
        if let ip = ip, !ip.isEmpty { body["ip"] = ip }
        
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.setValue(apiKey, forHTTPHeaderField: "X-API-Key")
        request.setValue("Swift-AuthClient/1.0", forHTTPHeaderField: "User-Agent")
        
        do {
            request.httpBody = try JSONSerialization.data(withJSONObject: body)
        } catch {
            completion(AuthResult(success: false, message: "JSON序列化失败: \(error.localizedDescription)"))
            return
        }
        
        session.dataTask(with: request) { data, response, error in
            if let error = error {
                completion(AuthResult(success: false, message: "网络请求失败: \(error.localizedDescription)"))
                return
            }
            
            guard let httpResponse = response as? HTTPURLResponse else {
                completion(AuthResult(success: false, message: "无效的响应"))
                return
            }
            
            guard let data = data else {
                completion(AuthResult(success: false, message: "空响应数据"))
                return
            }
            
            do {
                let json = try JSONSerialization.jsonObject(with: data) as? [String: Any]
                let code = json?["code"] as? Int ?? -1
                let msg = json?["msg"] as? String ?? ""
                let dataStr = json?["data"] as? String ?? "{}"
                
                if httpResponse.statusCode == 200 && code == 0 {
                    completion(AuthResult(success: true, message: msg, data: dataStr))
                } else {
                    completion(AuthResult(
                        success: false,
                        message: msg,
                        code: code,
                        httpCode: httpResponse.statusCode
                    ))
                }
            } catch {
                completion(AuthResult(success: false, message: "JSON解析失败"))
            }
        }.resume()
    }
    
    /// 清除缓存
    public func clearCache() {
        cache.removeAll()
    }
}

// ==================== 数据结构 ====================

/// 授权验证结果
public struct AuthResult {
    public let success: Bool
    public let message: String
    public let data: String
    public let fromCache: Bool
    public let code: Int
    public let httpCode: Int
    
    public init(
        success: Bool,
        message: String,
        data: String = "",
        fromCache: Bool = false,
        code: Int = 0,
        httpCode: Int = 200
    ) {
        self.success = success
        self.message = message
        self.data = data
        self.fromCache = fromCache
        self.code = code
        self.httpCode = httpCode
    }
}

/// 缓存项
private struct CacheItem {
    let data: String
    let timestamp: Date
}

/*
 // ========== 使用示例 ==========

 import UIKit

 class ViewController: UIViewController {
     override func viewDidLoad() {
         super.viewDidLoad()
         
         let client = AuthorizationClient.shared
         client.apiKey = "your_api_key_here"
         
         // 示例1：基础验证（回调方式）
         client.verify(authCode: "ABC123XYZ") { result in
             DispatchQueue.main.async {
                 if result.success {
                     print("✅ 授权验证成功！")
                     print("消息：\(result.message)")
                     print("数据：\(result.data)")
                 } else {
                     print("❌ 授权验证失败：\(result.message)")
                 }
             }
         }
         
         // 示例2：async/await方式（iOS 15+）
         Task {
             do {
                 let result = try await client.verify(authCode: "ABC123XYZ")
                 if result.success {
                     print("✅ 授权有效")
                 }
             } catch {
                 print("❌ 错误: \(error)")
             }
         }
         
         // 示例3：带域名的验证
         client.verify(authCode: "ABC123XYZ", domain: "example.com") { result in
             print(result)
         }
         
         // 示例4：清除缓存
         client.clearCache()
     }
 }

 // SwiftUI中使用示例
 struct LicenseView: View {
     @State private var isLicensed = false
     
     var body: some View {
         VStack {
             if isLicensed {
                 Text("✅ 授权已验证").foregroundColor(.green)
             } else {
                 Text("⏳ 正在验证...").foregroundColor(.orange)
             }
         }
         .onAppear {
             Task {
                 let result = try? await AuthorizationClient.shared.verify(authCode: "CODE")
                 isLicensed = result?.success ?? false
             }
         }
     }
 }
 */
