package com.xy.xyaicpzs.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * Coze认证服务
 * 提供通过JWT获取访问令牌的功能
 */
@Service
public class CozeAuthService {
    
    private static final Logger logger = LoggerFactory.getLogger(CozeAuthService.class);
    private static final String COZE_TOKEN_URL = "https://api.coze.cn/api/permission/oauth2/token";
    private static final String GRANT_TYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer";
    
    @Autowired
    private RestTemplate restTemplate;
    
    @Autowired
    private ObjectMapper objectMapper;
    
    /**
     * 通过JWT获取访问令牌
     *
     * @param jwt JWT令牌
     * @param durationSeconds 令牌有效期（秒）
     * @return 包含访问令牌和过期时间的Map
     */
    public Map<String, Object> getAccessToken(String jwt, Integer durationSeconds) {
        try {
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + jwt);
            
            // 设置请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("grant_type", GRANT_TYPE);
            if (durationSeconds != null && durationSeconds > 0) {
                requestBody.put("duration_seconds", durationSeconds);
            }
            
            // 创建请求实体
            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);
            
            // 发送请求
            ResponseEntity<String> response = restTemplate.postForEntity(COZE_TOKEN_URL, requestEntity, String.class);
            
            // 解析响应
            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
                JsonNode jsonNode = objectMapper.readTree(response.getBody());
                
                Map<String, Object> result = new HashMap<>();
                result.put("access_token", jsonNode.get("access_token").asText());
                result.put("expires_in", jsonNode.get("expires_in").asLong());
                
                return result;
            } else {
                throw new RuntimeException("获取访问令牌失败，HTTP状态码：" + response.getStatusCodeValue());
            }
            
        } catch (JsonProcessingException e) {
            logger.error("解析响应JSON失败", e);
            throw new RuntimeException("解析响应JSON失败: " + e.getMessage());
        } catch (Exception e) {
            logger.error("获取访问令牌失败", e);
            throw new RuntimeException("获取访问令牌失败: " + e.getMessage());
        }
    }
} 