import type { AxiosRequestConfig } from 'axios'

import obj from '@/utils/obj'

/** 同时有多个请求时，仅最后一个生效（与 xuexiaole-web 一致） */
export const only_last_id = 'on_last_id'
const only_last_req_id = 'only_last_req_id'
const controllers = {} as Record<string, AbortController>
const reqIds = {} as Record<string, string>

export type RequestConfig = AxiosRequestConfig & {
  [only_last_id]?: string
  [only_last_req_id]?: string
}

function processRequest(config: RequestConfig) {
  if (!config) return

  const onlyLastId = config[only_last_id]
  if (!onlyLastId) return

  let ctl = controllers[onlyLastId]
  if (ctl) {
    ctl.abort()
  }

  ctl = new AbortController()
  config.signal = ctl.signal
  controllers[onlyLastId] = ctl
  const reqId = obj.snowflakeId()
  reqIds[onlyLastId] = reqId
  config[only_last_req_id] = reqId
}

function processResponse(config: RequestConfig) {
  if (!config) return true
  const onlyLastId = config[only_last_id]
  if (!onlyLastId) return true

  const reqId = config[only_last_req_id]
  if (reqId === reqIds[onlyLastId]) {
    delete reqIds[onlyLastId]
    delete controllers[onlyLastId]
    return true
  }
  return false
}

export default {
  processRequest,
  processResponse,
}
