package com.cloudhandson.vpdbackoffice.web;

import com.cloudhandson.vpdbackoffice.service.McpChatbotService;
import com.cloudhandson.vpdbackoffice.service.BearerTokenService;
import com.cloudhandson.vpdbackoffice.mapper.UserMapper;
import jakarta.servlet.http.HttpServletRequest;
import java.util.List;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

@Controller
public class McpChatbotController {

  private final McpChatbotService chatbotService;
  private final BearerTokenService tokenService;
  private final UserMapper userMapper;

  public McpChatbotController(
      McpChatbotService chatbotService,
      BearerTokenService tokenService,
      UserMapper userMapper
  ) {
    this.chatbotService = chatbotService;
    this.tokenService = tokenService;
    this.userMapper = userMapper;
  }

  @GetMapping("/mcp-chatbot")
  public String page(Model model) {
    try {
      model.addAttribute("users", userMapper.findAll());
    } catch (DataAccessException exception) {
      model.addAttribute("users", List.of());
      model.addAttribute("runtimeError", RuntimeErrorMessages.dataAccess(exception));
    }
    return "mcp-chatbot";
  }

  @PostMapping("/mcp-chatbot")
  public String chat(
      @RequestParam(defaultValue = "vpd-live") String contextPath,
      @RequestParam(defaultValue = "") String question,
      @RequestParam(defaultValue = "") String bearerToken,
      @RequestParam(required = false) Long tempUserId,
      @RequestParam(defaultValue = "50") int limit,
      HttpServletRequest request,
      Model model
  ) {
    try {
      String serverOrigin = ServletUriComponentsBuilder.fromRequestUri(request)
          .replacePath(null)
          .replaceQuery(null)
          .build()
          .toUriString();
      String effectiveToken = bearerToken;
      Long temporaryKeyId = null;
      if (tempUserId != null) {
        var issued = tokenService.issueTemporaryToken(tempUserId, "MCP Chatbot 임시 실행");
        effectiveToken = issued.plainToken();
        temporaryKeyId = issued.keyId();
      }
      try {
        model.addAttribute("result", chatbotService.chat(serverOrigin, contextPath, question, effectiveToken, limit));
      } finally {
        if (temporaryKeyId != null) {
          tokenService.revokeToken(temporaryKeyId, "temporary chatbot completed");
        }
      }
    } catch (Exception e) {
      model.addAttribute("errorMessage", e.getMessage());
    }
    return "fragments/mcp-chatbot-result :: result";
  }
}
