import { ref } from 'vue'
import { http } from '@/api'

export interface QuickCmdItem {
  id: number
  name: string
  cmd: string
  is_builtin: boolean
  sort_order: number
}

export function sortQuickCommands(items: QuickCmdItem[]): QuickCmdItem[] {
  return [...items].sort((a, b) => {
    if (a.is_builtin !== b.is_builtin) return a.is_builtin ? 1 : -1
    if (a.sort_order !== b.sort_order) return a.sort_order - b.sort_order
    return a.id - b.id
  })
}

export function useTerminalQuickCommands() {
  const commands = ref<QuickCmdItem[]>([])
  const loading = ref(false)

  async function load() {
    loading.value = true
    try {
      const res = await http.get<QuickCmdItem[]>('/terminal/quick-commands')
      commands.value = sortQuickCommands(res || [])
    } catch {
      commands.value = []
      throw new Error('加载快捷命令失败')
    } finally {
      loading.value = false
    }
  }

  async function create(name: string, cmd: string) {
    await http.post('/terminal/quick-commands', { name: name.trim(), cmd: cmd.trim() })
    await load()
  }

  async function update(id: number, name: string, cmd: string) {
    await http.put(`/terminal/quick-commands/${id}`, { name: name.trim(), cmd: cmd.trim() })
    await load()
  }

  async function remove(id: number) {
    await http.delete(`/terminal/quick-commands/${id}`)
    await load()
  }

  async function reorder(customIds: number[]) {
    const res = await http.put<{ items: QuickCmdItem[] }>('/terminal/quick-commands/reorder', {
      ids: customIds,
    })
    commands.value = sortQuickCommands(res.items || [])
  }

  const customCommands = () => commands.value.filter((c) => !c.is_builtin)
  const builtinCommands = () => commands.value.filter((c) => c.is_builtin)

  return {
    commands,
    loading,
    load,
    create,
    update,
    remove,
    reorder,
    customCommands,
    builtinCommands,
  }
}
