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

import com.pablotj.ai.chat.application.dto.ConversationDto;
import com.pablotj.ai.chat.application.mapper.ConversationMapper;
import com.pablotj.ai.chat.domain.model.Conversation;
import com.pablotj.ai.chat.domain.model.ConversationSummary;
import com.pablotj.ai.chat.domain.repository.ConversationRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Use case for creating new conversations.
 * Handles the business logic for conversation creation with proper validation and persistence.
 */
@Service
@Transactional
public class CreateConversationUseCase {

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

    private final ConversationRepository conversationRepository;
    private final ConversationMapper conversationMapper;

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

    /**
     * Creates a new conversation with default settings.
     *
     * @return the created conversation DTO
     */
    public ConversationDto execute() {
        return execute(ConversationSummary.defaultSummary());
    }

    /**
     * Creates a new conversation with the specified summary.
     *
     * @param summary the conversation summary
     * @return the created conversation DTO
     */
    public ConversationDto execute(ConversationSummary summary) {
        logger.debug("Creating new conversation with summary: {}", summary);

        Conversation conversation = Conversation.createNew(summary);
        Conversation savedConversation = conversationRepository.save(conversation);

        logger.info("Successfully created conversation with ID: {}", savedConversation.getConversationId());

        return conversationMapper.toDto(savedConversation);
    }
}
