package com.usky.ai.controller.web;

import com.usky.ai.mapper.AiQuestionMapper;
import com.usky.ai.mapper.AiSessionMapper;
import com.usky.ai.domain.AiQuestion;
import com.usky.ai.domain.AiQuestionItem;
import com.usky.ai.domain.AiSession;
import com.usky.common.core.bean.ApiResult;
import com.usky.common.security.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/session")
public class AiSessionController {

    @Autowired
    private AiSessionMapper aiSessionMapper;

    @Autowired
    private AiQuestionMapper aiQuestionMapper;

    @GetMapping("/all")
    public List<AiSession> getAllSessions() {
        return aiSessionMapper.findAll();
    }

    @GetMapping("/current")
    public List<AiSession> getCurrentSessions(@RequestHeader("Authorization") String token) {
        // 解析 token 获取 userId
        Long userId = SecurityUtils.getUserId();
        return getSessionsByUserId(userId);
    }

    public List<AiSession> getSessionsByUserId(Long userId) {
        List<AiSession> sessions = aiSessionMapper.findByUserId(userId);

        for (AiSession session : sessions) {
            List<AiQuestion> questions = aiQuestionMapper.findQuestionsBySessionId(session.getSessionId());
            List<AiQuestionItem> itemList = new ArrayList<>();

            for (AiQuestion question : questions) {
                AiQuestionItem userItem = new AiQuestionItem("user", question.getQuestion());
                userItem.setId(question.getId());
                userItem.setSessionId(question.getSessionId());
                userItem.setUserId(question.getUserId());
                userItem.setUserName(question.getUserName());
                userItem.setAskTime(question.getAskTime());
                // 不设置 reasoningContent，因为 role 是 user

                itemList.add(userItem);

                AiQuestionItem assistantItem = new AiQuestionItem("assistant", null); // 初始化 content 为 null
                assistantItem.setId(question.getId());
                assistantItem.setSessionId(question.getSessionId());
                assistantItem.setUserId(question.getUserId());
                assistantItem.setUserName(question.getUserName());
                assistantItem.setAskTime(question.getAskTime());
                assistantItem.setReasoningContent(question.getAnswer()); // 设置 reasoningContent
                // 不设置 content，因为 role 是 assistant

                itemList.add(assistantItem);
            }

            session.setItemList(itemList);
        }

        return ApiResult.success(sessions).getData();
    }

    @PostMapping("/update")
    public ApiResult updateSession(@RequestBody AiSession aiSession) {
        aiSessionMapper.updateQuestion(aiSession.getSessionId(), aiSession.getQuestion());
        return ApiResult.success("更新会话成功");
    }

    @DeleteMapping("/delete")
    public ApiResult deleteSession(@RequestParam String sessionId) {
        try {
            aiSessionMapper.delete(sessionId);
            aiQuestionMapper.delete(sessionId);
            return ApiResult.success("删除会话成功");
        } catch (Exception e) {
            // 如果出现异常，可以记录日志或者返回错误信息
            log.error("删除会话失败", e);
            return ApiResult.error("删除会话失败");
        }
    }
}
