package com.hertz.modules.ai.controller;

import com.hertz.modules.ai.dto.ChatRequest;
import com.hertz.modules.ai.entity.Conversation;
import com.hertz.modules.ai.entity.Message;
import com.hertz.modules.ai.service.AiService;
import com.hertz.modules.ai.service.ConversationService;
import com.hertz.common.api.ApiResponse;
import com.hertz.common.exception.BusinessException;
import com.hertz.security.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.util.List;

@RestController
@RequestMapping("/api/ai")
@RequiredArgsConstructor
public class AiController {

    private final AiService aiService;
    private final ConversationService conversationService;

    @PostMapping("/chat")
    public ApiResponse<String> chat(@RequestBody ChatRequest request) {
        Long userId = null;
        if (request.getConversationId() != null) {
            userId = SecurityUtils.getCurrentUserId();
            if (userId == null) {
                throw new BusinessException(40100, "未登录或登录已过期");
            }
            conversationService.saveMessage(request.getConversationId(), "user", request.getMessage(), userId);
        }
        String response = aiService.chat(
                request.getMessage(),
                request.getTemperature(),
                request.getKnowledgeBaseId(),
                request.getConversationId(),
                userId
        );
        if (request.getConversationId() != null) {
            conversationService.saveMessage(request.getConversationId(), "assistant", response, userId);
        }
        return ApiResponse.ok(response);
    }

    @PostMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> streamChat(@RequestBody ChatRequest request) {
        // Frontend handles message persistence
        Long userId = null;
        if (request.getConversationId() != null) {
            userId = SecurityUtils.getCurrentUserId();
            if (userId == null) {
                throw new BusinessException(40100, "未登录或登录已过期");
            }
        }
        return aiService.streamChat(
                request.getMessage(),
                request.getTemperature(),
                request.getKnowledgeBaseId(),
                request.getConversationId(),
                userId
        );
    }

    @PostMapping("/conversations")
    public ApiResponse<Conversation> createConversation(@RequestBody Conversation conversation) {
        Long userId = SecurityUtils.getCurrentUserId();
        return ApiResponse.ok(conversationService.createConversation(conversation.getTitle(), userId));
    }

    @GetMapping("/conversations")
    public ApiResponse<List<Conversation>> listConversations() {
        Long userId = SecurityUtils.getCurrentUserId();
        return ApiResponse.ok(conversationService.getConversations(userId));
    }

    @DeleteMapping("/conversations/{id}")
    public ApiResponse<Void> deleteConversation(@PathVariable Long id) {
        Long userId = SecurityUtils.getCurrentUserId();
        conversationService.deleteConversation(id, userId);
        return ApiResponse.ok();
    }

    @PutMapping("/conversations/{id}")
    public ApiResponse<Void> updateConversation(@PathVariable Long id, @RequestBody Conversation conversation) {
        Long userId = SecurityUtils.getCurrentUserId();
        conversationService.updateConversationTitle(id, conversation.getTitle(), userId);
        return ApiResponse.ok();
    }

    @GetMapping("/conversations/search")
    public ApiResponse<List<Conversation>> searchConversations(@RequestParam String query) {
        Long userId = SecurityUtils.getCurrentUserId();
        return ApiResponse.ok(conversationService.searchConversations(query, userId));
    }

    @PostMapping("/conversations/{id}/messages")
    public ApiResponse<Message> saveMessage(@PathVariable Long id, @RequestBody Message message) {
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {
            throw new BusinessException(40100, "未登录或登录已过期");
        }
        return ApiResponse.ok(conversationService.saveMessage(id, message.getRole(), message.getContent(), userId));
    }

    @GetMapping("/conversations/{id}/messages")
    public ApiResponse<List<Message>> getMessages(@PathVariable Long id) {
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {
            throw new BusinessException(40100, "未登录或登录已过期");
        }
        return ApiResponse.ok(conversationService.getMessages(id, userId));
    }
}
