package shop.alien.store.controller;

import com.alibaba.fastjson2.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
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.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import shop.alien.entity.result.R;
import shop.alien.store.util.ai.AiAuthTokenUtil;

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

/**
 * 优店 QA（智能客服）相关代理接口，路径与第三方 AI 服务对齐。
 */
@Slf4j
@Api(tags = {"优店QA"})
@CrossOrigin
@RestController
@RequestMapping("/udian_qa")
@RequiredArgsConstructor
@RefreshScope
public class UdianQaController {

    private final RestTemplate restTemplate;
    private final AiAuthTokenUtil aiAuthTokenUtil;

    @Value("${ai.service.udian-qa-chat-history-url:http://124.93.18.180:9000/ai/smart-customer/api/v1/udian_qa/chat-history}")
    private String udianQaChatHistoryUrl;

    @ApiOperation("根据会话ID查询聊天历史（对外 GET，对内 POST 转发上游）")
    @GetMapping("/chat-history")
    public R chatHistory(@RequestParam(value = "session_id", required = false) String sessionId) {
        if (StringUtils.isBlank(sessionId)) {
            return R.fail("session_id不能为空");
        }

        Map<String, Object> requestBody = new HashMap<>(2);
        requestBody.put("session_id", sessionId);

        HttpHeaders aiHeaders = new HttpHeaders();
        String accessToken = aiAuthTokenUtil.getAccessToken();
        aiHeaders.setContentType(MediaType.APPLICATION_JSON);
        aiHeaders.set("Authorization", "Bearer " + accessToken);

        HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestBody, aiHeaders);
        try {
            log.info("调用优店QA聊天历史接口 入参------{}", requestBody);
            ResponseEntity<String> response = restTemplate.postForEntity(udianQaChatHistoryUrl, request, String.class);
            String respBody = response.getBody();
            log.info("调用优店QA聊天历史接口 返回------{}", respBody);
            if (StringUtils.isBlank(respBody)) {
                return R.fail("上游返回为空");
            }
            JSONObject json = JSONObject.parseObject(respBody);
            return R.data(json);
        } catch (Exception e) {
            log.error("调用优店QA聊天历史接口 异常------", e);
            return R.fail("请求失败");
        }
    }
}
