import { ideaApi } from '@/api'
import type { IdeaQuery } from '@/api/types'
import { t } from '@/i18n/i18n-helpers'
import { runWithCatch } from '@/composables/useStoreAction'
import { state } from './state'

/** 灵感 CRUD 子 store(共享全局 state) */
export function createIdeasStore() {
  /**
   * 加载灵感列表。
   *
   * F-260621-02:status/keyword/order_by 下沉后端 WHERE,取代前端 computed filter。
   * - 传 `query` → 多条件查询(状态/关键词/排序/分页)。
   * - 不传 → 全量(created_at DESC,等价旧行为)。
   */
  async function loadIdeas(query?: IdeaQuery) {
    await runWithCatch(state, t('ideas.err.loadFailed'), async () => {
      state.ideas = await ideaApi.list(query)
    })
  }

  async function createIdea(input: { title: string; description?: string; priority?: number; tags?: string; source?: string }) {
    const record = await runWithCatch(state, t('ideas.err.createFailed'), async () => {
      const r = await ideaApi.create(input)
      state.ideas.push(r)
      return r
    })
    return record ?? 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) {
    await runWithCatch(state, t('ideas.err.deleteFailed'), async () => {
      await ideaApi.delete(id)
      state.ideas = state.ideas.filter(i => i.id !== id)
    })
  }

  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
  }

  async function relateIdeas(subjectId: string, targetIds: string[]) {
    await runWithCatch(state, t('ideas.err.relateFailed'), async () => {
      await ideaApi.relateIdeas(subjectId, targetIds)
      await loadIdeas() // 后端已原子更新全部受影响灵感，刷新列表保持 store 一致
    })
  }

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