import { ref } from 'vue'
import { useToast } from './useToast'
import { comments } from '../utils/api'

export function useComments(postId) {
  const { showToast } = useToast()
  const commentsList = ref([])
  const loading = ref(false)
  const error = ref(null)

  const fetchComments = async () => {
    loading.value = true
    error.value = null
    try {
      const { data } = await comments.list(postId)
      commentsList.value = data.items || []
      return data
    } catch (err) {
      error.value = err.response?.data?.message || '获取评论列表失败'
      showToast(error.value, 'error')
      throw err
    } finally {
      loading.value = false
    }
  }

  const addComment = async (commentData) => {
    loading.value = true
    error.value = null
    try {
      const { data } = await comments.create(postId, commentData)
      commentsList.value.unshift(data.items?.[0] || data)
      showToast('评论成功', 'success')
      return data
    } catch (err) {
      error.value = err.response?.data?.message || '发表评论失败'
      showToast(error.value, 'error')
      throw err
    } finally {
      loading.value = false
    }
  }

  const updateComment = async (commentId, commentData) => {
    loading.value = true
    error.value = null
    try {
      const { data } = await comments.update(postId, commentId, commentData)
      const index = commentsList.value.findIndex(c => c.id === commentId)
      if (index !== -1) {
        commentsList.value[index] = data
      }
      showToast('更新成功', 'success')
      return data
    } catch (err) {
      error.value = err.response?.data?.message || '更新评论失败'
      showToast(error.value, 'error')
      throw err
    } finally {
      loading.value = false
    }
  }

  const deleteComment = async (commentId) => {
    loading.value = true
    error.value = null
    try {
      await comments.delete(postId, commentId)
      commentsList.value = commentsList.value.filter(c => c.id !== commentId)
      showToast('删除成功', 'success')
    } catch (err) {
      error.value = err.response?.data?.message || '删除评论失败'
      showToast(error.value, 'error')
      throw err
    } finally {
      loading.value = false
    }
  }

  return {
    commentsList,
    loading,
    error,
    fetchComments,
    addComment,
    updateComment,
    deleteComment
  }
}
