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

/** 任务 CRUD 子 store(共享全局 state) */
export function createTasksStore() {
  async function loadTasks(projectId?: string) {
    try {
      state.tasks = await taskApi.list(projectId)
    } catch (e: any) {
      state.error = e?.toString() ?? t('tasks.err.loadFailed')
    }
  }

  async function createTask(input: { project_id: string; title: string; description?: string; priority?: number; branch_name?: string; assignee?: string }) {
    try {
      const record = await taskApi.create(input)
      state.tasks.push(record)
      return record
    } catch (e: any) {
      state.error = e?.toString() ?? t('tasks.err.createFailed')
      return null
    }
  }

  async function updateTask(id: string, field: string, value: string) {
    try {
      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
      }
    } catch (e: any) {
      state.error = e?.toString() ?? t('tasks.err.updateFailed')
    }
  }

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

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