/**
 * 统一请求中转层
 *
 * 接口与 src/utils/request.ts 的 request 函数完全一致
 * 根据环境自动选择 axios 或原生 AJAX
 */

import { isNativeApp, ajaxGet, ajaxPost, ajaxPut, ajaxDelete } from '@/core/mxApi'
import type { MXAjaxResponse } from '@/core/mxApi'
import { request as axiosRequest } from '@/utils/request'
import type { ApiResponse } from '@/types/api'

// ============================================================
// Token 管理
// ============================================================

const TOKEN_KEY = 'token'

export const setToken = (token: string) => localStorage.setItem(TOKEN_KEY, token)
export const getToken = () => localStorage.getItem(TOKEN_KEY)
export const clearToken = () => localStorage.removeItem(TOKEN_KEY)

/**
 * 获取公共请求头
 */
export function getCommonHeaders(): Record<string, string> {
  const headers: Record<string, string> = {
    'Content-Type': 'application/json',
  }

  const token = getToken()
  if (token) {
    headers['Authorization'] = `Bearer ${token}`
  }

  return headers
}

// ============================================================
// 请求配置接口（与 request.ts 保持一致）
// ============================================================

export interface RequestConfig<T = unknown> {
  url: string
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'
  data?: T
  params?: Record<string, unknown>
  headers?: Record<string, string>
  auth?: { username: string; password: string } // HTTP Basic Auth
}

// ============================================================
// 核心中转函数
// ============================================================

/**
 * 统一请求中转
 *
 * 接口与 request.ts 的 request 函数完全一致
 * 调用方无需关心底层使用的是 axios 还是原生 AJAX
 *
 * @example
 * // 与 request.ts 用法完全一致
 * const res = await request<UserInfo>({ url: '/user/1' })
 * const res = await request<{ token: string }, LoginParams>({
 *   url: '/login',
 *   method: 'POST',
 *   data: { username: 'admin', password: '123' }
 * })
 */
export async function request<R = unknown, T = unknown>(
  config: RequestConfig<T>
): Promise<ApiResponse<R>> {
  const { url, method = 'GET', data, params, headers: customHeaders, auth } = config

  // 合并公共请求头和自定义请求头
  const headers = {
    ...getCommonHeaders(),
    ...customHeaders,
  }


  if (isNativeApp()) {
    return await nativeRequest<R, T>({ url, method, data, params, headers })
  } else {
    // 浏览器环境：axios 原生支持 auth 字段
    return await axiosRequest<R, T>({ url, method, data, params, headers, auth })
  }
}

// ============================================================
// 原生请求实现
// ============================================================

/**
 * 原生 AJAX 请求
 */
async function nativeRequest<R, T>(
  config: RequestConfig<T>
): Promise<ApiResponse<R>> {
  const { url, method, data, params } = config

  let response: MXAjaxResponse<unknown>

  switch (method) {
    case 'GET':
      response = await ajaxGet<R>(url, params)
      break
    case 'POST':
      response = await ajaxPost<R>(url, data)
      break
    case 'PUT':
      response = await ajaxPut<R>(url, data)
      break
    case 'DELETE':
      const id = params?.id as string
      response = await ajaxDelete<R>(url, id)
      break
    default:
      throw new Error(`不支持的请求方法: ${method}`)
  }

  // 包装成与 axios 拦截器一致的响应格式
  return {
    code: 0,
    message: 'success',
    data: response.data as R,
  } as ApiResponse<R>
}
