package com.pablotj.ia.chat.boot.persistence;

import com.pablotj.ia.chat.boot.domain.model.ChatIdentity;
import com.pablotj.ia.chat.boot.domain.model.ChatMessage;
import com.pablotj.ia.chat.boot.domain.port.ChatMessageStore;
import java.util.List;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
public class SqliteChatMessageStore implements ChatMessageStore {

    private final ChatMessageJpaRepository repository;

    public SqliteChatMessageStore(ChatMessageJpaRepository repository) {
        this.repository = repository;
    }

    @Override
    public List<ChatIdentity> getChats() {
        return repository.findFirstMessagePerSession().stream()
                .map(ChatMessageMapper::toEntityId)
                .toList();
    }

    @Override
    public List<ChatMessage> getMessages(String chatId) {
        return repository.findBySessionIdOrderByIdAsc(chatId)
                .stream()
                .map(ChatMessageMapper::toDomain)
                .toList();
    }

    @Override
    @Transactional
    public void saveMessages(String chatId, List<ChatMessage> messages) {
        repository.deleteBySessionId(chatId);
        List<ChatMessageEntity> entities = messages.stream()
                .map(m -> ChatMessageMapper.toEntity(chatId, m))
                .toList();
        repository.saveAll(entities);
    }
}