import type { IRequestOptions } from '../types'
import { useUserStore } from '@/stores/user'
import { APP_INFO } from '@/api/config'
import { getCurrentVersion } from '@/uni_modules/uni-upgrade-center-app/utils/call-check-version'

export function requestInterceptor(options: IRequestOptions): IRequestOptions {
  const headers = { ...(options.headers || {}) }

  // 更明确地调用 useUserStore
  let token = ''
  try {
    const userStore = typeof useUserStore === 'function' ? useUserStore() : null
    token = userStore?.token || uni.getStorageSync('token') || ''
  } catch (e) {
    token = uni.getStorageSync('token') || ''
  }

  if (token) headers.token = token

  // Content-Type：只有在没有 files 时才默认为 application/json
  if (!options.files && !headers['Content-Type']) {
    headers['Content-Type'] = 'application/json;charset=UTF-8'
  }

  getCurrentVersion().then((version_code: string) => {
    headers['version_code'] = version_code || ''
  })
  
  headers['appType'] = APP_INFO.TYPE
  
  return {
    ...options,
    header: headers,
  }
}
