import { API_ENDPOINTS, api } from '../config'

async function request<T = any>(url: string, method: string = 'POST', data?: any, auth: boolean = false): Promise<T> {
  const headers: Record<string, string> = { 'Content-Type': 'application/json' }
  if (auth) {
    const token = uni.getStorageSync('token') || ''
    if (token) headers['Authorization'] = `Bearer ${token}`
  }
  try {
    const res = await uni.request({ url: api(url), method, data, header: headers, timeout: 65000 })
    if (res.statusCode >= 200 && res.statusCode < 300) return res.data as T
    if (res.statusCode === 401) {
      uni.removeStorageSync('token'); uni.removeStorageSync('userInfo')
      uni.showToast({ title: '登录已过期', icon: 'none' })
      setTimeout(() => uni.navigateTo({ url: '/pages/login/login' }), 500)
      throw new Error('登录已过期')
    }
    throw new Error((res.data as any)?.message || '请求失败')
  } catch (e: any) {
    if (e.message === '登录已过期') throw e
    throw new Error(e.message || '网络错误')
  }
}

export const apiService = {
  user: {
    sendCode: (phone: string) => request(API_ENDPOINTS.USER.SEND_CODE, 'POST', { phone }),
    login: (phone: string, code: string) => request(API_ENDPOINTS.USER.LOGIN, 'POST', { phone, code }),
    wxLogin: (code: string) => request(API_ENDPOINTS.USER.WX_LOGIN, 'POST', { code }),
    getInfo: () => request(API_ENDPOINTS.USER.INFO, 'GET', undefined, true),
    update: (data: any) => request(API_ENDPOINTS.USER.UPDATE, 'PUT', data, true),
    usage: () => request(API_ENDPOINTS.USER.USAGE, 'GET', undefined, true),
  },
  interview: {
    create: (position: string) => request(API_ENDPOINTS.INTERVIEW.CREATE, 'POST', { position }, true),
    answer: (id: string, answer: string) => request(API_ENDPOINTS.INTERVIEW.ANSWER(id), 'POST', { answer }, true),
    complete: (id: string) => request(API_ENDPOINTS.INTERVIEW.COMPLETE(id), 'POST', undefined, true),
    get: (id: string) => request(API_ENDPOINTS.INTERVIEW.GET(id), 'GET', undefined, true),
    list: () => request(API_ENDPOINTS.INTERVIEW.LIST, 'GET', undefined, true),
    stats: () => request(API_ENDPOINTS.INTERVIEW.STATS, 'GET', undefined, true),
  },
  analyze: {
    diagnosis: (content: string) => request(API_ENDPOINTS.ANALYZE.DIAGNOSIS, 'POST', { content }),
    optimize: (content: string, direction: string) => request(API_ENDPOINTS.ANALYZE.OPTIMIZE, 'POST', { content, direction }),
  },
  resume: {
    create: (title: string, content: string, targetPosition?: string) =>
      request(API_ENDPOINTS.RESUME.CREATE, 'POST', { title, content, targetPosition }, true),
    list: () => request(API_ENDPOINTS.RESUME.LIST, 'GET', undefined, true),
    delete: (id: string) => request(API_ENDPOINTS.RESUME.DELETE(id), 'DELETE', undefined, true),
  },
}

export default apiService
