import { ref } from 'vue'
import { useApi } from './useApi'
import { useToast } from './useToast'
import { extractCollection } from '~/shared/utils/apiHelpers'

export interface ConstructeurCategorie {
  '@id'?: string
  id: string
  name: string
}

const categories = ref<ConstructeurCategorie[]>([])
const loading = ref(false)
const loaded = ref(false)

const sortByName = (items: ConstructeurCategorie[]): ConstructeurCategorie[] =>
  [...items].sort((a, b) => (a.name || '').localeCompare(b.name || ''))

export function useConstructeurCategories() {
  const { get, post } = useApi()
  const { showError } = useToast()

  const loadCategories = async (force = false): Promise<ConstructeurCategorie[]> => {
    if (loaded.value && !force) {
      return categories.value
    }
    loading.value = true
    try {
      const result = await get('/constructeur_categories?itemsPerPage=1000')
      if (result.success) {
        categories.value = sortByName(extractCollection<ConstructeurCategorie>(result.data))
        loaded.value = true
      }
      return categories.value
    }
    finally {
      loading.value = false
    }
  }

  const createCategory = async (name: string): Promise<ConstructeurCategorie | null> => {
    const trimmed = name.trim()
    if (!trimmed) {
      return null
    }
    const existing = categories.value.find(c => c.name.toLowerCase() === trimmed.toLowerCase())
    if (existing) {
      return existing
    }
    const result = await post('/constructeur_categories', { name: trimmed })
    if (result.success && result.data && !Array.isArray(result.data)) {
      const created = result.data as ConstructeurCategorie
      categories.value = sortByName([...categories.value, created])
      return created
    }
    if (result.error) {
      showError(result.error)
    }
    return null
  }

  return { categories, loading, loadCategories, createCategory }
}
