/**
 * 研究记录列表 Store
 * 管理列表数据、筛选条件和分页。
 */
import { ref } from 'vue'
import { defineStore } from 'pinia'
import {
  fetchRecordList,
  archiveRecord as archiveRecordApi,
  deleteRecord as deleteRecordApi,
} from '@/api/researchRecords'
import type { ResearchRecordSummary } from '@/types/research'

export const useResearchRecordListStore = defineStore('researchRecordList', () => {
  const records = ref<ResearchRecordSummary[]>([])
  const total = ref(0)
  const loading = ref(false)

  // Filter state
  const searchQuery = ref('')
  const statusFilter = ref<string | null>(null)
  const modeFilter = ref<string | null>(null)
  const templateFilter = ref<string | null>(null)
  const timeRange = ref<[string, string] | null>(null)
  const sortBy = ref<string>('updated_at')
  const sortOrder = ref<string>('desc')
  const showArchived = ref(false)
  const page = ref(1)
  const pageSize = ref(20)

  async function loadRecords() {
    loading.value = true
    try {
      const res = await fetchRecordList({
        q: searchQuery.value || undefined,
        status: statusFilter.value || undefined,
        mode: modeFilter.value || undefined,
        output_template: templateFilter.value || undefined,
        created_after: timeRange.value?.[0] || undefined,
        created_before: timeRange.value?.[1] || undefined,
        archived: showArchived.value || undefined,
        sort_by: sortBy.value || undefined,
        sort_order: sortOrder.value || undefined,
        limit: pageSize.value,
        offset: (page.value - 1) * pageSize.value,
      })
      records.value = res.records
      total.value = res.total
    } finally {
      loading.value = false
    }
  }

  async function archiveRecord(id: string) {
    await archiveRecordApi(id)
    await loadRecords()
  }

  async function removeRecord(id: string) {
    await deleteRecordApi(id)
    await loadRecords()
  }

  return {
    records,
    total,
    loading,
    searchQuery,
    statusFilter,
    modeFilter,
    templateFilter,
    timeRange,
    sortBy,
    sortOrder,
    showArchived,
    page,
    pageSize,
    loadRecords,
    archiveRecord,
    removeRecord,
  }
})
