import { useEffect } from 'react'
import { useTabStore } from '../stores/tabStore'
import { recentFilesRepository } from '../db/recentFilesRepository'

/**
 * 主进程事件注册 hook
 * 处理通过命令行或文件关联打开的文件
 */
export function useIpcListeners() {
  const createTab = useTabStore(s => s.createTab)

  useEffect(() => {
    if (!window.electronAPI) return
    const api = window.electronAPI
    const onOpen = (data: { filePath: string; content: string }) => {
      createTab(data.filePath, data.content)
      if (data.filePath) recentFilesRepository.add(data.filePath)
      setTimeout(() => useTabStore.getState().saveToDB(), 100)
    }
    return api.onFileOpenInTab(onOpen)
  }, [createTab])
}
