/* eslint-disable complexity */
/* eslint-disable prefer-promise-reject-errors */
import type { RequestOptions, ResponseData, ErrorResponse } from './types'
import { HTTP_STATUS, ERROR_MSG } from './config'
import router from '@/router/router'
import db from '@/utils/db'
import toast from '@/utils/hud'
import { storeToRefs } from 'pinia'
import { useUserStore } from '@/store'

// 请求拦截器
export const requestInterceptor = async (options: RequestOptions): Promise<RequestOptions> => {
  // 设置请求头
  const header: any = {
    ...options?.header,
  }
  const { token } = storeToRefs(useUserStore())

  // 获取token
  // 如果有token，添加到请求头
  if (token.value) {
    header['Authorization'] = `Bearer ${token.value}`
  }

  return {
    ...options,
    header,
  }
}

// 响应拦截器
export const responseInterceptor = async <T>(
  response: ResponseData<T>,
): Promise<ResponseData<T>> => {
  const { statusCode, data } = response as any
  // console.log('response', response)

  // 处理成功响应
  if (statusCode === HTTP_STATUS.SUCCESS && data.code === 200) {
    return response
  } else {
    throw {
      statusCode,
      errMsg: data.message || '网络问题，请稍后再试',
    }
  }
}

// 错误拦截器
export const errorInterceptor = (error: any): Promise<ErrorResponse> => {
  const { statusCode, errMsg } = error
  let toLogin = false

  let message = errMsg
  // 处理特定状态码
  switch (statusCode) {
    case HTTP_STATUS.AUTHENTICATE:
      toLogin = true
      message = message || ERROR_MSG.AUTH_ERROR
      break

    case HTTP_STATUS.FORBIDDEN:
      toLogin = true
      message = message || ERROR_MSG.FORBIDDEN_ERROR
      break

    case HTTP_STATUS.NOT_FOUND: {
      message = message || ERROR_MSG.NOT_FOUND_ERROR
      break
    }

    case HTTP_STATUS.SERVER_ERROR:
    case HTTP_STATUS.BAD_GATEWAY:
    case HTTP_STATUS.SERVICE_UNAVAILABLE:
    case HTTP_STATUS.GATEWAY_TIMEOUT:
      message = message || ERROR_MSG.SERVER_ERROR
      break

    default:
      message = message || ERROR_MSG.DEFAULT_ERROR
      break
  }

  // 显示错误提示
  let showed = false
  if (message) {
    toast.error(message)
    showed = true
    if (toLogin) {
      router.toLogin()
    }
  }

  return Promise.reject({
    code: -1,
    message,
    data: error,
    showed,
  })
}
