import {ref} from "vue"
import {ChatRepository} from "@/infrastructure/repositories/ChatRepository"

export function useChatService(chatConfig) {
  const messages = ref([])
  const input = ref("")
  const isLoading = ref(false)

  const chatRepository = new ChatRepository(chatConfig)

  async function sendMessage(text = null) {
    const messageText = text || input.value.trim()
    if (!messageText || isLoading.value) return

    // Add user message
    const userMessage = {
      id: Date.now(),
      role: "user",
      content: messageText,
      timestamp: Date.now(),
    }
    messages.value.push(userMessage)

    // Clear input
    input.value = ""
    isLoading.value = true

    // Add typing indicator
    const typingMessage = {
      id: Date.now() + 1,
      role: "assistant",
      content: "",
      typing: true,
    }
    messages.value.push(typingMessage)

    try {
      // Get response from repository
      const response = await chatRepository.getResponse(messageText)

      // Remove typing indicator
      messages.value.pop()

      // Add assistant response
      const assistantMessage = {
        id: Date.now() + 2,
        role: "assistant",
        content: response,
        timestamp: Date.now(),
      }
      messages.value.push(assistantMessage)
    } catch (error) {
      console.error("Error getting chat response:", error)

      // Remove typing indicator
      messages.value.pop()

      // Add error message
      const errorMessage = {
        id: Date.now() + 2,
        role: "assistant",
        content: "Lo siento, ha ocurrido un error. Por favor, intenta de nuevo.",
        timestamp: Date.now(),
      }
      messages.value.push(errorMessage)
    } finally {
      isLoading.value = false
    }
  }

  return {
    messages,
    input,
    isLoading,
    sendMessage,
  }
}
