package shop.alien.store.controller;

import com.alibaba.fastjson2.JSONObject;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import shop.alien.entity.store.dto.AiQuestionClassificationRequestDto;
import shop.alien.store.service.AiQuestionClassificationService;

/**
 * 问题分类控制器
 *
 * @author system
 * @since 2025-01-XX
 */
@Slf4j
@Api(tags = {"AI问题分类"})
@CrossOrigin
@RestController
@RequestMapping("/questionClassification")
@RequiredArgsConstructor
@RefreshScope
public class AiQuestionClassificationController {

    private final AiQuestionClassificationService questionClassificationService;

    /**
     * 问题分类接口
     *
     * @param requestDto 问题分类请求DTO
     * @return AI接口返回的原始响应
     */
    @ApiOperation(value = "问题分类", notes = "对用户问题进行AI分类")
    @ApiOperationSupport(order = 1)
    @PostMapping("/classify")
    public ResponseEntity<String> classify(@RequestBody AiQuestionClassificationRequestDto requestDto) {
        log.info("收到问题分类请求，问题：{}", requestDto != null ? requestDto.getQuestion() : null);
        
        // 参数校验
        if (requestDto == null || !StringUtils.hasText(requestDto.getQuestion())) {
            log.warn("问题分类请求参数为空或问题文本为空");
            JSONObject errorResponse = new JSONObject();
            errorResponse.put("code", 400);
            errorResponse.put("message", "问题文本不能为空");
            return ResponseEntity.badRequest().body(errorResponse.toJSONString());
        }
        
        try {
            String result = questionClassificationService.classify(requestDto);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("问题分类失败，问题：{}", requestDto.getQuestion(), e);
            JSONObject errorResponse = new JSONObject();
            errorResponse.put("code", 500);
            errorResponse.put("message", "问题分类失败：" + e.getMessage());
            return ResponseEntity.status(500).body(errorResponse.toJSONString());
        }
    }
}

