// ============================================
// 数据库状态管理 Store
// ============================================

import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import {
  initDatabase,
  getAllReferences,
  getReferenceById as dbGetReferenceById,
  getReferencesByType as dbGetReferencesByType,
  addReference as dbAddReference,
  updateReference as dbUpdateReference,
  deleteReference as dbDeleteReference,
  getAllParadigms,
  addParadigm as dbAddParadigm,
  updateParadigm as dbUpdateParadigm,
  deleteParadigm as dbDeleteParadigm,
  getConfig,
  setConfig,
  exportAsJSON,
  resetDatabase,
  saveToIndexedDB
} from '../db/index.js'

export const useDatabaseStore = defineStore('database', () => {
  // ============================================
  // 状态
  // ============================================
  
  const isInitialized = ref(false)
  const isLoading = ref(false)
  const error = ref(null)
  
  // 素材数据
  const references = ref([])
  
  // 范式数据
  const paradigms = ref([])
  
  // ============================================
  // 初始化
  // ============================================
  
  const initialize = async () => {
    if (isInitialized.value) return true
    
    isLoading.value = true
    error.value = null
    
    try {
      await initDatabase()
      
      // 加载所有数据
      await refreshReferences()
      await refreshParadigms()
      
      isInitialized.value = true
      console.log('✅ 数据库 Store 初始化完成')
      return true
    } catch (err) {
      error.value = err.message
      console.error('❌ 数据库初始化失败:', err)
      return false
    } finally {
      isLoading.value = false
    }
  }
  
  // ============================================
  // 素材库操作
  // ============================================
  
  const refreshReferences = async () => {
    references.value = getAllReferences()
  }
  
  const getReferenceById = (id) => {
    return references.value.find(r => r.id === id) || dbGetReferenceById(id)
  }
  
  const getReferencesByType = (type) => {
    if (type === 'all') return references.value
    return references.value.filter(r => r.type === type)
  }
  
  const getReferencesByDimension = (dimensionId) => {
    const results = []
    
    references.value.forEach(ref => {
      ref.excerpts?.forEach(excerpt => {
        if (excerpt.applicableDimensions?.includes(dimensionId)) {
          results.push({
            referenceId: ref.id,
            referenceTitle: ref.title,
            referenceType: ref.type,
            source: ref.source,
            ...excerpt
          })
        }
      })
    })
    
    return results
  }
  
  const addReference = async (reference) => {
    const id = dbAddReference(reference)
    await refreshReferences()
    return id
  }
  
  const updateReference = async (id, updates) => {
    dbUpdateReference(id, updates)
    await refreshReferences()
  }
  
  const deleteReference = async (id) => {
    dbDeleteReference(id)
    await refreshReferences()
  }
  
  // ============================================
  // 范式操作
  // ============================================
  
  const refreshParadigms = async () => {
    paradigms.value = getAllParadigms()
  }
  
  const getParadigmById = (id) => {
    return paradigms.value.find(p => p.id === id)
  }
  
  const addParadigm = async (paradigm) => {
    const id = dbAddParadigm(paradigm)
    await refreshParadigms()
    return id
  }
  
  const updateParadigm = async (id, updates) => {
    dbUpdateParadigm(id, updates)
    await refreshParadigms()
  }
  
  const deleteParadigm = async (id) => {
    dbDeleteParadigm(id)
    await refreshParadigms()
  }
  
  // ============================================
  // 配置操作
  // ============================================
  
  const getUserConfig = (key, defaultValue = null) => {
    return getConfig(key, defaultValue)
  }
  
  const setUserConfig = (key, value) => {
    return setConfig(key, value)
  }
  
  // ============================================
  // 数据导入导出
  // ============================================
  
  const exportData = () => {
    return exportAsJSON()
  }
  
  const reset = async () => {
    await resetDatabase()
    await refreshReferences()
    await refreshParadigms()
  }
  
  const save = async () => {
    await saveToIndexedDB()
  }
  
  // ============================================
  // 计算属性
  // ============================================
  
  const referenceCount = computed(() => references.value.length)
  const paradigmCount = computed(() => paradigms.value.length)
  const customParadigmCount = computed(() => paradigms.value.filter(p => p.isCustom).length)
  
  const referencesByType = computed(() => {
    const grouped = {}
    references.value.forEach(ref => {
      if (!grouped[ref.type]) {
        grouped[ref.type] = []
      }
      grouped[ref.type].push(ref)
    })
    return grouped
  })
  
  // ============================================
  // 返回
  // ============================================
  
  return {
    // 状态
    isInitialized,
    isLoading,
    error,
    references,
    paradigms,
    
    // 初始化
    initialize,
    
    // 素材操作
    refreshReferences,
    getReferenceById,
    getReferencesByType,
    getReferencesByDimension,
    addReference,
    updateReference,
    deleteReference,
    
    // 范式操作
    refreshParadigms,
    getParadigmById,
    addParadigm,
    updateParadigm,
    deleteParadigm,
    
    // 配置操作
    getUserConfig,
    setUserConfig,
    
    // 导入导出
    exportData,
    reset,
    save,
    
    // 计算属性
    referenceCount,
    paradigmCount,
    customParadigmCount,
    referencesByType
  }
})
