import http from '@/utils/request'

const TOOL_LIST_CACHE_TTL = 5 * 60 * 1000
const toolListCache = new Map<string, { timestamp: number, response: any }>()
const toolListPending = new Map<string, Promise<any>>()

function getToolListCacheKey(params?: { userRoles?: string[] }) {
  return JSON.stringify({
    toolType: '03',
    userRoles: params?.userRoles || [],
  })
}

/**
 * 查询推荐问题列表
 * @params
 */
export function fetchQuestionList(data: any) {
  return http.post('/config-center/api/commonconfig/mobile/v1/query_config_list', data)
}

/**
 * 查询工具列表
 * @params params.userRoles: 角色数组，用于按角色返回工具
 */
export function fetchToolList(params?: { userRoles?: string[] }) {
  const cacheKey = getToolListCacheKey(params)
  const now = Date.now()
  const cached = toolListCache.get(cacheKey)
  if (cached && now - cached.timestamp < TOOL_LIST_CACHE_TTL) {
    return Promise.resolve(cached.response)
  }

  const pending = toolListPending.get(cacheKey)
  if (pending) {
    return pending
  }

  const requestBody: Record<string, string | string[]> = {
    toolType: '03',
    userRoles: [],
  }
  if (params?.userRoles)
    requestBody.userRoles = params.userRoles
  const request = http.post('/config-center/api/tool/mobile/v1/get_tool_list', requestBody)
    .then((res) => {
      toolListCache.set(cacheKey, {
        timestamp: Date.now(),
        response: res,
      })
      toolListPending.delete(cacheKey)
      return res
    })
    .catch((error) => {
      toolListPending.delete(cacheKey)
      throw error
    })

  toolListPending.set(cacheKey, request)
  return request
}

/**
 * 查询 提质增效 推荐问题列表
 * @params
 * conversationId: 会话id
 * busiType: 业务类型，固定值 '01'
 * recordType: 记录类型，固定值 'A14'
 */
export function fetchEfficiencyQuestionList(data: any) {
  return http.post('/conversation/api/conversation/mobile/v1/query_strategy_recommend_question', data)
}
