/**
 * 文档检索状态管理
 * 集中管理搜索关键词、筛选条件、分页、检索结果和聚合统计。
 * 供 SearchView 和 useSearch composable 消费。
 */
import { defineStore } from 'pinia'
import { ref, reactive } from 'vue'
import { searchDocuments } from '@/api/search'
import type { SearchParams, SearchFilters, DocumentResult, SearchResponse } from '@/types/search'

export const useSearchStore = defineStore('search', () => {
  const query = ref('')
  const filters = reactive<SearchFilters>({
    issuing_org: undefined,
    doc_type: undefined,
    knowledge_category: undefined,
    document_scene_type: undefined,
    signer: undefined,
    publish_year: undefined,
    doc_number: undefined,
    date_from: undefined,
    date_to: undefined,
    subject_words: undefined,
    search_scope: 'all',
  })
  const results = ref<DocumentResult[]>([])
  const total = ref(0)
  const page = ref(1)
  const pageSize = ref(20)
  const loading = ref(false)
  const aggregations = ref<Record<string, { key: string; count: number }[]>>({})

  /** 执行搜索；resetPage=true 时重置到第一页 */
  async function search(resetPage = true) {
    if (!query.value.trim()) return
    if (resetPage) page.value = 1
    loading.value = true
    try {
      const params: SearchParams = {
        query: query.value,
        filters: { ...filters },
        page: page.value,
        page_size: pageSize.value,
      }
      const res: SearchResponse = await searchDocuments(params)
      results.value = res.documents
      total.value = res.total
      aggregations.value = res.aggregations || {}
    } catch (err) {
      console.error('Search failed:', err)
      results.value = []
      total.value = 0
    } finally {
      loading.value = false
    }
  }

  /** 翻页：更新页码后执行搜索（不重置到第一页） */
  async function changePage(p: number) {
    page.value = p
    await search(false)
  }

  /** 重置所有筛选条件为初始值 */
  function resetFilters() {
    filters.issuing_org = undefined
    filters.doc_type = undefined
    filters.knowledge_category = undefined
    filters.document_scene_type = undefined
    filters.signer = undefined
    filters.publish_year = undefined
    filters.doc_number = undefined
    filters.date_from = undefined
    filters.date_to = undefined
    filters.subject_words = undefined
    filters.search_scope = 'all'
  }

  return {
    query, filters, results, total, page, pageSize, loading, aggregations,
    search, changePage, resetFilters,
  }
})
