import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useApi } from '../composables/useApi.js'
import { useAsyncAction } from '../composables/useAsyncAction.js'

export const useMLStore = defineStore('ml', () => {
  const api = useApi()
  const settings = ref(null)
  const { loading, error, run } = useAsyncAction({ errorAs: 'message' })

  async function loadSettings() {
    await run(async () => {
      settings.value = await api.get('/api/ml/settings')
    })
  }

  async function patchSettings(patch) {
    settings.value = await api.patch('/api/ml/settings', { body: patch })
  }

  async function triggerBackfill() {
    await api.post('/api/ml/backfill')
  }

  // Server-authoritative list of supported embedders for the model dropdown.
  async function embedderModels() {
    const r = await api.get('/api/ml/embedder-models')
    return r.models || []
  }

  return {
    settings, loading, error,
    loadSettings, patchSettings, triggerBackfill, embedderModels
  }
})
