import {useToast} from 'vue-toast-notification'

const toast = useToast({
  position: 'top-right',
  duration: 3000,
  dismissible: true,
  queue: false,
  pauseOnHover: true,
})

class ChatService {
  async getChats() {
    try {
        const response = await fetch("/api/v1/conversations", {method: "GET"})
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      return await response.json()
    } catch (error) {
      console.error("Error fetching chats:", error)
      toast.error("Error loading chats")
      throw error
    }
  }

  async createChat() {
    try {
        const response = await fetch("/api/v1/conversations", {
        method: "POST",
      })
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      return await response.json()
    } catch (error) {
      console.error("Error creating chat:", error)
      toast.error("Could not create chat")
      throw error
    }
  }

  async getChatMessages(chatId) {
    try {
        const response = await fetch(`/api/v1/conversations/${chatId}/messages`)
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      return await response.json()
    } catch (error) {
      console.error("Error fetching messages:", error)
      toast.error("Failed to load messages")
      throw error
    }
  }

  async sendMessage(chatId, prompt) {
    try {
        const response = await fetch(`/api/v1/conversations/${chatId}/messages`, {
            method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
            body: JSON.stringify({content: prompt}),
      })
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`)
      }
      return await response.json()
    } catch (error) {
      console.error("Error sending message:", error)
      toast.error("Message could not be sent")
      throw error
    }
  }
}

export const chatService = new ChatService()