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

// `artist` retired in FC-2d-vii-c (provenance is its own axis), `meta` +
// `rating` retired by operator 2026-05-26 (alembic 0023 drops them from
// the enum). KIND_COLOR keeps `archive` + `post` so any legacy
// system-managed tag still renders with a neutral color.
const KIND_OPTIONS = [
  { value: 'general',   label: 'General',   icon: 'mdi-tag' },
  { value: 'character', label: 'Character', icon: 'mdi-account-circle' },
  { value: 'fandom',    label: 'Fandom',    icon: 'mdi-book-open-page-variant' },
  { value: 'series',    label: 'Series',    icon: 'mdi-bookshelf' }
]

const KIND_COLOR = {
  character: 'info',
  fandom:    'secondary',
  series:    'warning',
  general:   'on-surface',
  archive:   'on-surface',
  post:      'on-surface'
}

export const useTagStore = defineStore('tags', () => {
  const api = useApi()
  const fandomCache = ref([])

  async function autocomplete(q, kind = null, limit = 20) {
    if (!q || !q.trim()) return []
    const params = { q, limit }
    if (kind) params.kind = kind
    return await api.get('/api/tags/autocomplete', { params })
  }

  async function loadFandoms() {
    // List ALL fandoms via the cursor-paged tag directory. (#712: the old impl
    // abused /tags/autocomplete with q=' ', which the backend strips to empty
    // and returns [] — so the picker showed no existing fandoms.)
    const all = []
    let cursor = null
    do {
      const params = { kind: 'fandom', limit: 200 }
      if (cursor) params.cursor = cursor
      const body = await api.get('/api/tags/directory', { params })
      all.push(...(body.cards || []))
      cursor = body.next_cursor
    } while (cursor)
    fandomCache.value = all
    return all
  }

  async function createFandom(name) {
    const fandom = await api.post('/api/tags', { body: { name, kind: 'fandom' } })
    fandomCache.value = [...fandomCache.value, {
      id: fandom.id, name: fandom.name, kind: 'fandom',
      fandom_id: null, fandom_name: null, image_count: 0
    }]
    return fandom
  }

  // Set / change / clear a character tag's fandom. fandomId null clears it.
  // Throws ApiError (status 409, body.target) on a name collision in the
  // target fandom; pass { merge: true } to resolve it by merging this tag
  // into the existing character. Returns the updated/surviving tag.
  async function setFandom(tagId, fandomId, { merge = false } = {}) {
    const body = { fandom_id: fandomId ?? null }
    if (merge) body.merge = true
    return await api.patch(`/api/tags/${tagId}`, { body })
  }

  function kindOptions() { return KIND_OPTIONS }
  function colorFor(kind) { return KIND_COLOR[kind] || 'on-surface' }

  return {
    fandomCache, autocomplete, loadFandoms, createFandom, setFandom,
    kindOptions, colorFor
  }
})
