import { defineStore } from 'pinia'
import { ref } from 'vue'
import * as api from '../api/client.js'

export const useTopicsStore = defineStore('topics', () => {
  const topics = ref([])
  const loading = ref(false)
  const error = ref(null)

  async function fetchTopics() {
    loading.value = true
    error.value = null
    try {
      const data = await api.listTopics()
      topics.value = data.topics
    } catch (e) {
      error.value = e.message
    } finally {
      loading.value = false
    }
  }

  async function addTopic(payload) {
    const topic = await api.createTopic(payload)
    topics.value.push(topic)
    return topic
  }

  async function editTopic(id, patch) {
    const updated = await api.updateTopic(id, patch)
    const idx = topics.value.findIndex(t => t.id === id)
    if (idx !== -1) topics.value[idx] = updated
    return updated
  }

  async function removeTopic(id) {
    await api.deleteTopic(id)
    topics.value = topics.value.filter(t => t.id !== id)
  }

  return { topics, loading, error, fetchTopics, addTopic, editTopic, removeTopic }
})
