/**
 * API Error handling composable
 * 统一的 API 错误处理
 */

import { ref } from 'vue'
import { Message } from '@arco-design/web-vue'

export interface ApiErrorState {
  hasError: boolean
  message: string
  code?: string | number
}

export function useApiError() {
  const error = ref<ApiErrorState>({
    hasError: false,
    message: ''
  })

  const setError = (err: Error | string | unknown, defaultMessage: string = '操作失败') => {
    let message = defaultMessage
    let code: string | number | undefined

    if (err instanceof Error) {
      message = err.message || defaultMessage
    } else if (typeof err === 'string') {
      message = err
    } else if (err && typeof err === 'object' && 'message' in err) {
      message = (err as any).message || defaultMessage
      if ('code' in err) code = (err as any).code
    }

    error.value = {
      hasError: true,
      message,
      code
    }

    return { message, code }
  }

  const showError = (err: Error | string | unknown, defaultMessage: string = '操作失败') => {
    const { message } = setError(err, defaultMessage)
    Message.error(message)
  }

  const clearError = () => {
    error.value = {
      hasError: false,
      message: ''
    }
  }

  return {
    error,
    setError,
    showError,
    clearError
  }
}
