package com.pablotj.ia.chat.boot.adapter.controller;

import com.pablotj.ia.chat.boot.application.usecase.ChatHistoryUseCase;
import com.pablotj.ia.chat.boot.application.usecase.ChatUseCase;
import com.pablotj.ia.chat.boot.domain.model.ChatIdentity;
import com.pablotj.ia.chat.boot.domain.model.ChatMessage;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ObjectUtils;
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.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/v1/chats")
public class ChatRestController {

    private static final Logger LOGGER = LogManager.getLogger(ChatRestController.class);

    private final ChatUseCase chatUseCase;
    private final ChatHistoryUseCase chatHistoryUseCase;

    public ChatRestController(ChatUseCase chatUseCase, ChatHistoryUseCase chatHistoryUseCase) {
        this.chatUseCase = chatUseCase;
        this.chatHistoryUseCase = chatHistoryUseCase;
    }

    @GetMapping
    public ResponseEntity<List<ChatIdentity>> getChatHistory() {
        LOGGER.debug("Accessing to chat");
        return ResponseEntity.ok(chatHistoryUseCase.chats());
    }

    @GetMapping("{chatId}")
    public ResponseEntity<List<ChatMessage>> getChatMessages(@PathVariable("chatId") String chatId) {
        LOGGER.debug("Accessing to chat messages");
        return ResponseEntity.ok(chatUseCase.getMessages(chatId));
    }

    @PostMapping(produces = "application/json")
    public ResponseEntity<String> newChat() {
        return ResponseEntity.ok(UUID.randomUUID().toString());
    }

    @PutMapping(value = "{chatId}", consumes = "application/x-www-form-urlencoded", produces = "application/json")
    public ResponseEntity<ChatMessage> handleChat(@PathVariable("chatId") String chatId, @RequestParam("prompt") String prompt) {
        if (ObjectUtils.isEmpty(chatId)) {
            throw new IllegalArgumentException("Chat id cannot be empty");
        }
        ChatMessage reply;
        try {
            reply = chatUseCase.processUserPrompt(prompt, chatId);
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            reply = new ChatMessage(chatId, "bot", e.getMessage(), new Date());
        }
        return ResponseEntity.ok(reply);
    }
}