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

export const useMessageActions = () => {
  const [markReadLoading, setMarkReadLoading] = useState(false)
  const [markReadError, setMarkReadError] = useState<Error | null>(null)
  const [batchMarkReadLoading, setBatchMarkReadLoading] = useState(false)
  const [batchMarkReadError, setBatchMarkReadError] = useState<Error | null>(null)
  const [deleteLoading, setDeleteLoading] = useState(false)
  const [deleteError, setDeleteError] = useState<Error | null>(null)

  const markRead = async (id: string) => {
    setMarkReadLoading(true)
    setMarkReadError(null)
    try {
      const messageController = root.get(MessageController)
      await messageController.markRead({ id })
    } catch (error) {
      setMarkReadError(error as Error)
    } finally {
      setMarkReadLoading(false)
    }
  }

  const batchMarkRead = async (ids: string[]) => {
    setBatchMarkReadLoading(true)
    setBatchMarkReadError(null)
    try {
      const messageController = root.get(MessageController)
      await messageController.batchMarkRead({ ids })
    } catch (error) {
      setBatchMarkReadError(error as Error)
    } finally {
      setBatchMarkReadLoading(false)
    }
  }

  const deleteMessage = async (id: string) => {
    setDeleteLoading(true)
    setDeleteError(null)
    try {
      const messageController = root.get(MessageController)
      await messageController.delete({ id })
    } catch (error) {
      setDeleteError(error as Error)
    } finally {
      setDeleteLoading(false)
    }
  }

  return {
    markRead,
    markReadLoading,
    markReadError,
    batchMarkRead,
    batchMarkReadLoading,
    batchMarkReadError,
    deleteMessage,
    deleteLoading,
    deleteError,
  }
}
