import { root } from '@repo/core'
import { MessageController, type UnreadCountResult } from '@repo/sdk'
import { useState } from 'react'

export const useMessageUnreadCount = () => {
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<Error | null>(null)
  const [data, setData] = useState<UnreadCountResult>()

  const refetch = async () => {
    setLoading(true)
    setError(null)
    try {
      const messageController = root.get(MessageController)
      const result = await messageController.getUnreadCount()
      setData(result)
    } catch (err) {
      setError(err as Error)
    } finally {
      setLoading(false)
    }
  }

  return {
    data,
    loading,
    error,
    refetch,
  }
}
