package shop.alien.store.service.impl;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
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.util.StringUtils;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestTemplate;
import shop.alien.entity.store.dto.AiQuestionClassificationRequestDto;
import shop.alien.store.service.AiQuestionClassificationService;
import shop.alien.store.util.ai.AiAuthTokenUtil;

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

/**
 * 问题分类服务实现类
 *
 * @author system
 * @since 2025-01-XX
 */
@Slf4j
@Service
@RequiredArgsConstructor
@RefreshScope
public class AiQuestionClassificationServiceImpl implements AiQuestionClassificationService {

    private final AiAuthTokenUtil aiAuthTokenUtil;

    private final RestTemplate restTemplate;

    @Value("${third-party-ai-question-classification.base-url}")
    private String questionClassificationUrl;

    @Override
    public String classify(AiQuestionClassificationRequestDto requestDto) {
        log.info("开始调用问题分类接口，问题：{}", requestDto.getQuestion());

        // 获取访问令牌
        String accessToken = aiAuthTokenUtil.getAccessToken();
        if (!StringUtils.hasText(accessToken)) {
            log.error("调用问题分类接口失败，获取accessToken失败");
            throw new RuntimeException("获取访问令牌失败");
        }

        // 构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("question", requestDto.getQuestion());

        // 构建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + accessToken);

        HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestBody, headers);

        try {
            log.info("调用问题分类接口，URL：{}，请求参数：{}", questionClassificationUrl, requestBody);
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(
                    questionClassificationUrl, request, String.class);

            log.info("问题分类接口调用成功，响应状态：{}，响应体：{}",
                    responseEntity.getStatusCode(), responseEntity.getBody());

            // 直接返回响应体
            return responseEntity.getBody();

        } catch (HttpClientErrorException e) {
            log.error("调用问题分类接口返回客户端错误，状态码：{}，响应体：{}，URL：{}",
                    e.getStatusCode(), e.getResponseBodyAsString(), questionClassificationUrl, e);
            throw new RuntimeException("调用问题分类接口失败：" + e.getMessage(), e);
        } catch (HttpServerErrorException e) {
            log.error("调用问题分类接口返回服务器错误，状态码：{}，响应体：{}，URL：{}",
                    e.getStatusCode(), e.getResponseBodyAsString(), questionClassificationUrl, e);
            throw new RuntimeException("调用问题分类接口失败：" + e.getMessage(), e);
        } catch (Exception e) {
            log.error("调用问题分类接口异常，URL：{}，异常信息：{}", questionClassificationUrl, e.getMessage(), e);
            throw new RuntimeException("调用问题分类接口异常：" + e.getMessage(), e);
        }
    }
}