package com.pablotj.ia.chat.boot.application.session;

import com.pablotj.ia.chat.boot.domain.model.ChatMessage;
import com.pablotj.ia.chat.boot.domain.port.ChatMessageStore;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

@Component
public class ChatSessionManager {

    private final ChatMessageStore chatMessageStore;

    public ChatSessionManager(ChatMessageStore chatMessageStore) {
        this.chatMessageStore = chatMessageStore;
    }

    public List<ChatMessage> getMessages(String chatId) {
        List<ChatMessage> messages = chatMessageStore.getMessages(chatId);
        List<ChatMessage> filteredMessages = new ArrayList<>(messages);

        if (ObjectUtils.isEmpty(filteredMessages)) {
            return new ArrayList<>();
        } else {
            filteredMessages.removeIf(m -> ObjectUtils.isEmpty(m.text()));
        }
        return filteredMessages;
    }

    public void setMessages(String chatId, List<ChatMessage> messages) {
        messages.removeIf(m -> ObjectUtils.isEmpty(m.text()));
        chatMessageStore.saveMessages(chatId, messages);
    }
}