import { taskApi } from '@/api'
import type { TaskQuery, ProjectId } from '@/api/types'
import { t } from '@/i18n/i18n-helpers'
import { runWithCatch } from '@/composables/useStoreAction'
import { state } from './state'

/** 任务 CRUD 子 store(共享全局 state) */
export function createTasksStore() {
  /**
   * 加载任务列表。
   *
   * **双签名向后兼容**(F-260621-02):
   * - `loadTasks(projectId?)`:旧签名,仅项目过滤(等价 `loadTasks({ project_id: projectId })`)。
   * - `loadTasks(query?)`:新签名,多条件(status/keyword/...)走后端 WHERE。
   *
   * 不传 → 全量未删任务(created_at DESC,等价改造前 list_active)。
   * status/keyword 下沉后端 WHERE(P1/P2),取代 Tasks.vue 旧的前端内存 filter。
   */
  async function loadTasks(queryOrProjectId?: TaskQuery | string) {
    await runWithCatch(state, t('tasks.err.loadFailed'), async () => {
      state.tasks = await taskApi.list(queryOrProjectId)
    })
  }

  async function createTask(input: { project_id: ProjectId; title: string; description?: string; priority?: number; branch_name?: string; assignee?: string; idea_id?: string }) {
    const record = await runWithCatch(state, t('tasks.err.createFailed'), async () => {
      const r = await taskApi.create(input)
      state.tasks.push(r)
      return r
    })
    return record ?? null
  }

  async function updateTask(id: string, field: string, value: string) {
    await runWithCatch(state, t('tasks.err.updateFailed'), async () => {
      await taskApi.update(id, field, value)
      const idx = state.tasks.findIndex(t => t.id === id)
      if (idx >= 0) {
        (state.tasks[idx] as any)[field] = value
      }
    })
  }

  async function deleteTask(id: string) {
    await runWithCatch(state, t('tasks.err.deleteFailed'), async () => {
      await taskApi.delete(id)
      state.tasks = state.tasks.filter(t => t.id !== id)
    })
  }

  return {
    loadTasks,
    createTask,
    updateTask,
    deleteTask,
  }
}
