import axios from 'axios'

const baseURL = '/api'

/**
 * 翻译文本，根据文本长度动态设置超时
 * 按 20 字符/秒的最低速率 × 2 倍冗余计算
 */
export function translateText(text) {
  const charsPerSec = 20
  const multiplier = 2
  const minTimeout = 30000
  const dynamicTimeout = Math.max(minTimeout, Math.ceil((text.length / charsPerSec) * multiplier) * 1000)

  return axios.post(`${baseURL}/translations/translate`, { text }, {
    timeout: dynamicTimeout
  }).then(response => {
    const res = response.data
    if (res.code !== 200) {
      return Promise.reject(new Error(res.message || '翻译失败'))
    }
    return res
  })
}
