package org.example.petshopdesktop.api.endpoints;

import com.fasterxml.jackson.core.type.TypeReference;
import org.example.petshopdesktop.api.ApiClient;
import org.example.petshopdesktop.api.dto.chat.ConversationRequest;
import org.example.petshopdesktop.api.dto.chat.ConversationResponse;
import org.example.petshopdesktop.api.dto.chat.MessageRequest;
import org.example.petshopdesktop.api.dto.chat.MessageResponse;
import org.example.petshopdesktop.api.dto.chat.UpdateConversationRequest;
import java.io.File;
import java.util.List;

public class ChatApi {
    private static final ChatApi INSTANCE = new ChatApi();
    private final ApiClient apiClient;

    private ChatApi() {
        this.apiClient = ApiClient.getInstance();
    }

    public static ChatApi getInstance() {
        return INSTANCE;
    }

    public List<ConversationResponse> listConversations() throws Exception {
        String response = apiClient.getRawResponse("/api/v1/chat/conversations");
        return apiClient.getObjectMapper().readValue(response, new TypeReference<List<ConversationResponse>>() {});
    }

    public ConversationResponse createConversation(ConversationRequest request) throws Exception {
        return apiClient.post("/api/v1/chat/conversations", request, ConversationResponse.class);
    }

    public ConversationResponse getConversation(Long id) throws Exception {
        return apiClient.get("/api/v1/chat/conversations/" + id, ConversationResponse.class);
    }

    public List<MessageResponse> listMessages(Long conversationId) throws Exception {
        String response = apiClient.getRawResponse("/api/v1/chat/conversations/" + conversationId + "/messages");
        return apiClient.getObjectMapper().readValue(response, new TypeReference<List<MessageResponse>>() {});
    }

    public MessageResponse sendMessage(Long conversationId, MessageRequest request) throws Exception {
        return apiClient.post("/api/v1/chat/conversations/" + conversationId + "/messages", request, MessageResponse.class);
    }

    public MessageResponse sendMessageWithAttachment(Long conversationId, File file, String content) throws Exception {
        String path = "/api/v1/chat/conversations/" + conversationId + "/attachments";
        return apiClient.postMultipartWithText(path, "file", file.toPath(), "content", content, MessageResponse.class);
    }

    public ConversationResponse updateConversation(Long id, UpdateConversationRequest request) throws Exception {
        return apiClient.put("/api/v1/chat/conversations/" + id, request, ConversationResponse.class);
    }
}
