import { ideaApi } from '@/api'
import { t } from '@/i18n/i18n-helpers'
import { state } from './state'

/** 灵感 CRUD 子 store(共享全局 state) */
export function createIdeasStore() {
  async function loadIdeas() {
    try {
      state.ideas = await ideaApi.list()
    } catch (e: any) {
      state.error = e?.toString() ?? t('ideas.err.loadFailed')
    }
  }

  async function createIdea(input: { title: string; description?: string; priority?: number; tags?: string; source?: string }) {
    try {
      const record = await ideaApi.create(input)
      state.ideas.push(record)
      return record
    } catch (e: any) {
      state.error = e?.toString() ?? t('ideas.err.createFailed')
      return null
    }
  }

  async function updateIdea(id: string, field: string, value: string) {
    await ideaApi.update(id, field, value)
    const idx = state.ideas.findIndex(i => i.id === id)
    if (idx >= 0) {
      (state.ideas[idx] as any)[field] = value
    }
  }

  async function deleteIdea(id: string) {
    try {
      await ideaApi.delete(id)
      state.ideas = state.ideas.filter(i => i.id !== id)
    } catch (e: any) {
      state.error = e?.toString() ?? t('ideas.err.deleteFailed')
    }
  }

  async function evaluateIdea(id: string) {
    const record = await ideaApi.evaluate(id)
    const idx = state.ideas.findIndex(i => i.id === id)
    if (idx >= 0) state.ideas[idx] = record
    return record
  }

  async function promoteIdea(id: string) {
    const res = await ideaApi.promote(id)
    await loadIdeas() // 后端已回写 status=promoted/promoted_to，刷新列表
    return res
  }

  return {
    loadIdeas,
    createIdea,
    updateIdea,
    deleteIdea,
    evaluateIdea,
    promoteIdea,
  }
}
