package tech.easyflow.admin.controller.ai;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import tech.easyflow.chatlog.domain.dto.ChatHistoryPage;
import tech.easyflow.chatlog.domain.dto.ChatMessageRecord;
import tech.easyflow.chatlog.domain.dto.ChatSessionPage;
import tech.easyflow.chatlog.domain.dto.ChatSessionSummary;
import tech.easyflow.chatlog.domain.query.ChatPageQuery;
import tech.easyflow.chatlog.domain.query.ChatSessionFilterQuery;
import tech.easyflow.chatlog.service.ChatHistoryManageService;
import tech.easyflow.common.domain.Result;
import tech.easyflow.common.entity.LoginAccount;
import tech.easyflow.common.satoken.util.SaTokenUtil;
import tech.easyflow.common.web.jsonbody.JsonBody;

import java.math.BigInteger;
import java.util.List;

@RestController
@RequestMapping("/api/v1/chatHistory")
public class ChatHistoryController {

    private final ChatHistoryManageService chatHistoryManageService;

    public ChatHistoryController(ChatHistoryManageService chatHistoryManageService) {
        this.chatHistoryManageService = chatHistoryManageService;
    }

    @GetMapping("/sessions")
    public Result<ChatSessionPage> listSessions(ChatSessionFilterQuery query) {
        return Result.ok(chatHistoryManageService.queryAdminSessions(query));
    }

    @GetMapping("/sessions/{sessionId}")
    public Result<ChatSessionSummary> getSession(@PathVariable BigInteger sessionId) {
        return Result.ok(chatHistoryManageService.getAdminSession(sessionId));
    }

    @GetMapping("/sessions/{sessionId}/messages")
    public Result<ChatHistoryPage> queryMessages(@PathVariable BigInteger sessionId, ChatPageQuery query) {
        return Result.ok(chatHistoryManageService.queryAdminMessages(sessionId, query));
    }

    @GetMapping("/sessions/{sessionId}/rounds/{roundId}/variants")
    public Result<List<ChatMessageRecord>> listRoundVariants(@PathVariable BigInteger sessionId,
                                                             @PathVariable BigInteger roundId) {
        return Result.ok(chatHistoryManageService.listAdminRoundVariants(sessionId, roundId));
    }

    @PostMapping("/sessions/{sessionId}/rounds/{roundId}/selectVariant")
    public Result<ChatMessageRecord> selectRoundVariant(@PathVariable BigInteger sessionId,
                                                        @PathVariable BigInteger roundId,
                                                        @JsonBody(value = "variantIndex", required = true) Integer variantIndex) {
        LoginAccount account = SaTokenUtil.getLoginAccount();
        return Result.ok(chatHistoryManageService.selectAdminRoundVariant(sessionId, roundId, variantIndex, account.getId()));
    }
}
