import { useState, useCallback, useEffect, useMemo, useRef } from 'react'
import { saveConversation, getConversations, deleteConversation } from '../services/chatHistory.js'

/**
 * 封装历史会话的 CRUD + state 管理
 * @param {'create'|'eval'|'sandbox'} type
 */
export function useConversationHistory(type, user = null) {
  const [conversationId, setConversationId] = useState(null)
  const [showHistory, setShowHistory] = useState(false)
  const [version, setVersion] = useState(0)
  const idRef = useRef(null)
  const userKey = `${user?.email || ''}|${user?.phone || ''}|${user?.id || ''}`

  useEffect(() => {
    idRef.current = null
    setConversationId(null)
  }, [userKey])

  // 打开抽屉时自动刷新列表
  const conversations = useMemo(
    () => (showHistory ? getConversations(type, user) : []),
    [type, userKey, showHistory, version]
  )

  const save = useCallback((messages, extra = {}) => {
    if (messages.length <= 1) return // 没实质对话不保存
    const id = saveConversation(type, { id: idRef.current, messages, ...extra }, user)
    if (id !== idRef.current) {
      idRef.current = id
      setConversationId(id)
    }
    setVersion(v => v + 1)
  }, [type, userKey])

  const load = useCallback((conv) => {
    idRef.current = conv.id
    setConversationId(conv.id)
    setShowHistory(false)
    return conv
  }, [])

  const remove = useCallback((convOrId) => {
    const cid = typeof convOrId === 'object' ? convOrId.id : convOrId
    deleteConversation(type, cid, user)
    setVersion(v => v + 1)
  }, [type, userKey])

  const reset = useCallback(() => {
    idRef.current = null
    setConversationId(null)
  }, [])

  return { conversationId, idRef, showHistory, setShowHistory, conversations, save, load, remove, reset }
}
