import type { UseFetchOptions } from '#app'
import type { IInterceptor, IConfig, IOption } from './interface'

class Request {
  public baseURL: string
  public interceptor: IInterceptor

  constructor({ baseURL, interceptor }: IConfig) {
    this.baseURL = baseURL
    this.interceptor = interceptor as IInterceptor
  }

  request<T = BasicResponse>({ url, method, params, data, options }: IOption<T>): Promise<T> {
    const newOptions: UseFetchOptions<T> = {
      baseURL: this.baseURL,
      method,
      query: params,
      body: data,
      ...options,
      onRequest: this.interceptor?.onRequest,
      onRequestError: this.interceptor?.onRequestError,
      onResponse: this.interceptor?.onResponse,
      onResponseError: this.interceptor?.onResponseError,
    }
    return this.requestPipeline(url, newOptions)
  }

  // 请求管道处理具体细节
  requestPipeline<T = any>(url: string, options: UseFetchOptions<T>): Promise<T> {
    return $fetch<T>(url, options as any)
  }
}

export default Request
