package com.pablotj.ai.chat.application.usecase;

import com.pablotj.ai.chat.application.dto.ConversationMessageDto;
import com.pablotj.ai.chat.application.mapper.ConversationMapper;
import com.pablotj.ai.chat.domain.exception.ConversationNotFoundException;
import com.pablotj.ai.chat.domain.model.Conversation;
import com.pablotj.ai.chat.domain.model.ConversationId;
import com.pablotj.ai.chat.domain.repository.ConversationRepository;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Use case for retrieving messages from a specific conversation.
 */
@Service
@Transactional(readOnly = true)
public class GetConversationMessagesUseCase {

    private static final Logger logger = LoggerFactory.getLogger(GetConversationMessagesUseCase.class);

    private final ConversationRepository conversationRepository;
    private final ConversationMapper conversationMapper;

    public GetConversationMessagesUseCase(
            ConversationRepository conversationRepository,
            ConversationMapper conversationMapper) {
        this.conversationRepository = conversationRepository;
        this.conversationMapper = conversationMapper;
    }

    /**
     * Retrieves all messages from the specified conversation.
     *
     * @param conversationIdValue the conversation ID as string
     * @return list of conversation message DTOs
     * @throws ConversationNotFoundException if the conversation doesn't exist
     */
    public List<ConversationMessageDto> execute(String conversationIdValue) {
        ConversationId conversationId = ConversationId.of(conversationIdValue);

        logger.debug("Retrieving messages for conversation: {}", conversationId);

        Conversation conversation = conversationRepository
                .findById(conversationId)
                .orElseThrow(() -> new ConversationNotFoundException(conversationId));

        List<ConversationMessageDto> messages = conversation.getMessages()
                .stream()
                .map(conversationMapper::toMessageDto)
                .toList();

        logger.debug("Retrieved {} messages for conversation: {}", messages.size(), conversationId);

        return messages;
    }
}
