import { ref } from 'vue'
import { defineStore } from 'pinia'
import {
  getWorkflows, getWorkflow, createWorkflow, saveWorkflow, deleteWorkflow
} from '../api/workflow'

export const useWorkflowStore = defineStore('workflow', () => {
  const workflows = ref([])
  const current = ref(null)
  const loading = ref(false)

  // 分页搜索
  const currentPage = ref(1)
  const pageSize = ref(12)
  const total = ref(0)
  // 不带过滤条件的全量计数，用于左侧"全部智能体"badge 的稳定显示
  const unfilteredTotal = ref(0)
  const totalPages = ref(1)
  const searchKeyword = ref('')
  const selectedCategoryId = ref(null)

  async function fetchList() {
    loading.value = true
    try {
      const params = {
        page: currentPage.value,
        size: pageSize.value
      }
      if (searchKeyword.value) params.search = searchKeyword.value
      if (selectedCategoryId.value) params.categoryId = selectedCategoryId.value

      const { data } = await getWorkflows(params)
      workflows.value = data.content || []
      total.value = data.total || 0
      totalPages.value = data.totalPages || 1
      currentPage.value = data.page || 1
      // 无过滤条件时同步更新全量计数
      if (!selectedCategoryId.value && !searchKeyword.value) {
        unfilteredTotal.value = total.value
      }
    } finally {
      loading.value = false
    }
  }

  async function fetchOne(nameOrId) {
    const { data } = await getWorkflow(nameOrId)
    current.value = data
    return data
  }

  async function create({ name, displayName, description }) {
    const { data } = await createWorkflow({ name, displayName, description })
    return data
  }

  async function save(nameOrId, payload) {
    const { data } = await saveWorkflow(nameOrId, payload)
    return data
  }

  async function remove(nameOrId) {
    await deleteWorkflow(nameOrId)
    fetchList()
  }

  function setPage(p) {
    currentPage.value = p
    fetchList()
  }

  function setSearch(kw) {
    searchKeyword.value = kw
    currentPage.value = 1
    fetchList()
  }

  function setCategory(catId) {
    selectedCategoryId.value = catId
    currentPage.value = 1
    fetchList()
  }

  return {
    workflows, current, loading,
    currentPage, pageSize, total, unfilteredTotal, totalPages, searchKeyword, selectedCategoryId,
    fetchList, fetchOne, create, save, remove,
    setPage, setSearch, setCategory
  }
})
