import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { apiClient } from '@/api/client'

// ── Types ────────────────────────────────────────────────

export interface IndexRule {
  id: string
  action: 'include' | 'exclude'
  scope: string          // 'all' | 'post_type:post' | 'taxonomy:category' | …
  termId?: number | null
  termName?: string | null
  postId?: number | null
  postTitle?: string | null
}

export interface ScopeOption {
  value: string
  label: string
  group: string | null
  needsTerm: boolean
  taxonomy?: string
  needsPost?: boolean
  postType?: string
}

export interface TaxonomyTerm {
  id: number
  name: string
  slug: string
  count: number
}

export interface ScopePostItem {
  id: number
  title: string
  slug: string
  url: string
  postType: string
}

// ── Hooks ────────────────────────────────────────────────

/**
 * GET /index/rules — Load the saved rule set for the given language.
 */
export function useIndexRules(language?: string) {
  const params = language ? { language } : {}
  return useQuery<{ success: boolean; data: { rules: IndexRule[] } }>({
    queryKey: ['index-rules', language ?? '__default__'],
    queryFn: () => apiClient.get('index/rules', params),
    staleTime: 30_000,
  })
}

/**
 * POST /index/rules — Persist rules only (no indexing).
 */
export function useSaveRules(language?: string) {
  const queryClient = useQueryClient()
  return useMutation({
    mutationFn: (rules: IndexRule[]) =>
      apiClient.post('index/rules', { rules, language }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['index-rules'] })
    },
  })
}

/**
 * GET /index/scope-options — Hierarchical dropdown data.
 */
export function useScopeOptions() {
  return useQuery<{ success: boolean; data: ScopeOption[] }>({
    queryKey: ['index-scope-options'],
    queryFn: () => apiClient.get('index/scope-options'),
    staleTime: 60_000,
  })
}

/**
 * GET /index/terms?taxonomy=xxx — Terms for a taxonomy.
 */
export function useTaxonomyTerms(taxonomy: string | null | undefined) {
  return useQuery<{ success: boolean; data: TaxonomyTerm[] }>({
    queryKey: ['index-terms', taxonomy],
    queryFn: () => apiClient.get(`index/terms?taxonomy=${encodeURIComponent(taxonomy!)}`),
    enabled: !!taxonomy,
    staleTime: 60_000,
  })
}

/**
 * GET /index/posts?post_type=xxx&search=yyy — Published posts for single-item rule selector.
 */
export function useScopePosts(postType: string | null | undefined, search: string, limit = 20) {
  return useQuery<{ success: boolean; data: ScopePostItem[] }>({
    queryKey: ['index-scope-posts', postType, search, limit],
    queryFn: () =>
      apiClient.get(
        `index/posts?post_type=${encodeURIComponent(postType!)}&search=${encodeURIComponent(search)}&limit=${encodeURIComponent(String(limit))}`
      ),
    enabled: !!postType,
    staleTime: 30_000,
  })
}

/**
 * POST /index/save-and-index — Save rules + start indexing.
 */
export function useSaveAndIndex(language?: string) {
  const queryClient = useQueryClient()
  return useMutation<
    { success: boolean; data: { job_id: string; total_items: number; resolved_ids: number } },
    Error,
    IndexRule[]
  >({
    mutationFn: (rules: IndexRule[]) =>
      apiClient.post('index/save-and-index', { rules, language }),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['index-rules'] })
      queryClient.invalidateQueries({ queryKey: ['knowledge-base'] })
    },
  })
}

/**
 * POST /index/reindex-stale — Find and re-index stale content.
 */
export function useReindexStale() {
  const queryClient = useQueryClient()
  return useMutation<
    { success: boolean; data: { stale_count: number; job_id?: string; message: string } },
    Error,
    { days: number }
  >({
    mutationFn: (params) =>
      apiClient.post('index/reindex-stale', params),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['knowledge-base'] })
    },
  })
}
