/**
 * SaaS授权系统 - Java客户端
 * 
 * 使用说明：
 * 1. 修改 API_KEY 为您的真实API密钥
 * 2. 将此文件中的类导入到您的Java项目中
 * 3. 调用验证：AuthorizationClient.verify("AUTH_CODE")
 * 
 * 依赖：OkHttp3 (推荐) 或 Java 11+ HttpClient
 * Maven: com.squareup.okhttp3:okhttp:4.12.0
 *
 * @author 授权系统
 * @version 1.0.0
 */

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONObject;

public class AuthorizationClient {
    
    // ==================== 配置区 ====================
    
    /**
     * API密钥（从开发者中心获取）
     * 网址：https://kuio.cn/user/developer
     */
    public static final String API_KEY = "your_api_key_here";
    
    /**
     * API接口地址
     */
    public static final String BASE_URL = "https://kuio.cn/api/saas";
    
    /**
     * 缓存配置
     */
    private static boolean CACHE_ENABLED = true;
    private static long CACHE_DURATION = 1800; // 缓存时间（秒）30分钟
    private static Map<String, String> cache = new HashMap<>();
    private static Map<Long, Long> cacheTime = new HashMap<>();
    
    // HTTP客户端
    private static HttpClient httpClient = HttpClient.newBuilder()
        .connectTimeout(Duration.ofSeconds(10))
        .build();
    
    // ==================== 核心方法 ====================
    
    /**
     * 验证授权（带缓存）
     */
    public static AuthResult verify(String authCode) throws IOException, InterruptedException {
        return verify(authCode, null, null);
    }
    
    /**
     * 验证授权（带域名和IP）
     */
    public static AuthResult verify(String authCode, String domain, String ip) throws IOException, InterruptedException {
        // 1. 尝试从缓存读取
        if (CACHE_ENABLED && cache.containsKey(authCode)) {
            long cachedTime = cacheTime.getOrDefault(authCode, 0L);
            if (System.currentTimeMillis() / 1000 - cachedTime < CACHE_DURATION) {
                return new AuthResult(true, "授权验证成功（缓存）", cache.get(authCode), true);
            }
        }
        
        // 2. 调用API验证
        AuthResult result = verifyFromApi(authCode, domain, ip);
        
        // 3. 成功则写入缓存
        if (result.isSuccess() && CACHE_ENABLED) {
            cache.put(authCode, result.getData());
            cacheTime.put(authCode, System.currentTimeMillis() / 1000);
        }
        
        return result;
    }
    
    /**
     * 从API验证授权（不使用缓存）
     */
    private static AuthResult verifyFromApi(String authCode, String domain, String ip) throws IOException, InterruptedException {
        String url = BASE_URL + "/verify";
        
        // 构建JSON请求体
        JSONObject jsonBody = new JSONObject();
        jsonBody.put("authcode", authCode);
        if (domain != null && !domain.isEmpty()) jsonBody.put("domain", domain);
        if (ip != null && !ip.isEmpty()) jsonBody.put("ip", ip);
        
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(url))
            .header("Content-Type", "application/json")
            .header("X-API-Key", API_KEY)
            .header("User-Agent", "Java-AuthClient/1.0")
            .POST(HttpRequest.BodyPublishers.ofString(jsonBody.toString()))
            .build();
        
        HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
        JSONObject responseBody = new JSONObject(response.body());
        
        if (response.statusCode() == 200 && responseBody.optInt("code", -1) == 0) {
            return new AuthResult(
                true,
                responseBody.optString("msg", "授权验证成功"),
                responseBody.optString("data", "{}"),
                false
            );
        } else {
            return new AuthResult(
                false,
                responseBody.optString("msg", "授权验证失败"),
                "",
                false,
                responseBody.optInt("code", -1),
                response.statusCode()
            );
        }
    }
    
    /**
     * 清除缓存
     */
    public static void clearCache() {
        cache.clear();
        cacheTime.clear();
    }
    
    // ==================== 结果类 ====================
    
    public static class AuthResult {
        private boolean success;
        private String message;
        private String data;
        boolean fromCache;
        int code;
        int httpCode;
        
        public AuthResult(boolean success, String message, String data, boolean fromCache) {
            this(success, message, data, fromCache, 0, 200);
        }
        
        public AuthResult(boolean success, String message, String data, boolean fromCache, int code, int httpCode) {
            this.success = success;
            this.message = message;
            this.data = data;
            this.fromCache = fromCache;
            this.code = code;
            this.httpCode = httpCode;
        }
        
        public boolean isSuccess() { return success; }
        public String getMessage() { return message; }
        public String getData() { return data; }
        public boolean isFromCache() { return fromCache; }
        public int getCode() { return code; }
        public int getHttpCode() { return httpCode; }
        
        @Override
        public String toString() {
            return "AuthResult{success=" + success + ", message='" + message + "', fromCache=" + fromCache + "}";
        }
    }
}

/*
// ========== 使用示例 ==========

public class Example {
    public static void main(String[] args) {
        try {
            // 示例1：基础验证
            AuthResult result = AuthorizationClient.verify("ABC123XYZ");
            
            if (result.isSuccess()) {
                System.out.println("✅ 授权验证成功！");
                System.out.println("消息：" + result.getMessage());
                System.out.println("数据：" + result.getData());
            } else {
                System.out.println("❌ 授权验证失败：" + result.getMessage());
            }
            
            // 示例2：带域名的验证
            AuthResult result2 = AuthorizationClient.verify("ABC123XYZ", "example.com", null);
            
            // 示例3：快速检查
            if (AuthorizationClient.verify("CODE").isSuccess()) {
                System.out.println("✅ 授权有效");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
*/
