package com.backendsys.modules.ai.chat.controller;

import com.backendsys.modules.ai.chat.entity.Chat;
import com.backendsys.modules.ai.chat.service.ChatService;
import com.backendsys.modules.common.config.security.utils.SecurityUtil;
import com.backendsys.modules.common.utils.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Validated
@RestController
@Tag(name = "AI对话")
public class ChatController {

    @Autowired
    private ChatService chatService;


    /**
     * 前端判断：
     * 当在对话历史中切换模型时，(内容 > 0 时)
     * 提示："不同模型会受之前的回答影响，导致准确度下降，是否要清空当前的对话内容？"
     */
    @Operation(summary = "发起对话")
    @PreAuthorize("@sr.hasPermission('31')")
    @PostMapping("/api/ai/chat/sendChat")
    public Result sendChat(@Validated(Chat.Create.class) @RequestBody Chat chat) {
        return Result.success().put("data", chatService.sendChat(chat));
    }

    @Operation(summary = "中止对话")
    @PreAuthorize("@sr.hasPermission('31')")
    @PostMapping("/api/ai/chat/abortChat")
    public Result abortChat(@Validated(Chat.Abort.class) @RequestBody Chat chat) {
        return Result.success().put("data", chatService.abortChat(chat));
    }

    @Operation(summary = "获取我的对话")
    @PreAuthorize("@sr.hasPermission('31')")
    @GetMapping("/api/ai/chat/getChatList")
    public Result getChatList(@Validated(Chat.Detail.class) Chat chat) {
        chat.setUser_id(SecurityUtil.getUserId());
        chat.setDel_flag(-1);
        return Result.success().put("data", chatService.selectChatList(chat));
    }

    @Operation(summary = "删除我的对话内容 (软删除)")
    @PreAuthorize("@sr.hasPermission('31')")
    @DeleteMapping("/api/ai/chat/deleteChat")
    public Result deleteChat(@Validated(Chat.Delete.class) @RequestBody Chat chat) {
        // 仅能删除自己的
        chat.setUser_id(SecurityUtil.getUserId());
        return Result.success().put("data", chatService.deleteChat(chat));
    }

    @Operation(summary = "删除单条对话内容 (软删除)")
    @PreAuthorize("@sr.hasPermission('31')")
    @DeleteMapping("/api/ai/chat/deleteChatOne")
    public Result deleteChatOne(@Validated(Chat.DeleteOne.class) @RequestBody Chat chat) {
        // 仅能删除自己的
        chat.setUser_id(SecurityUtil.getUserId());
        return Result.success().put("data", chatService.deleteChatOne(chat));
    }


}
