"use client"

import { useEffect, useMemo, useRef } from "react"
import { useMutation, useQuery } from "convex/react"
import { api } from "@/convex/_generated/api"
import type { TicketCategory } from "@/lib/schemas/category"

export function useTicketCategories(tenantId: string) {
  const categories = useQuery(
    api.categories.list,
    tenantId ? { tenantId } : "skip"
  ) as TicketCategory[] | undefined
  const ensureDefaults = useMutation(api.categories.ensureDefaults)
  const initializingRef = useRef(false)

  useEffect(() => {
    if (!categories) return
    if (categories.length > 0) {
      initializingRef.current = false
      return
    }
    if (initializingRef.current) return
    initializingRef.current = true
    ensureDefaults({ tenantId }).catch(() => {
      initializingRef.current = false
    })
  }, [categories, ensureDefaults, tenantId])

  return useMemo(
    () => ({
      categories: categories ?? [],
      isLoading: categories === undefined,
    }),
    [categories]
  )
}
