import http from '@/utils/request'
import { safeSessionStorageGetItem } from '@/lib/utils'

/**
 * 查询用户历史会话列表
 * @params
 */
export function fetchQueryUserConversationPage<T>(data: T) {
  return http.post('/conversation/api/conversation/mobile/v1/query_user_conversation_page', data)
}

/**
 * 创建会话
 * @params { * }
 */
export function fetchCreateConversation<T>(data: T) {
  return http.post('/conversation/api/conversation/mobile/v1/create_conversation', data as Record<string, any>)
}

/**
 * 查询用户问答历史
 * @params { * }
 */
export function fetchUserQaRecordPage(conversationId: string, toolId?: string) {
  return http.post('/conversation/api/conversation/mobile/v1/query_user_qa_record_list', { conversationId, toolId: toolId || '' })
}

/**
 * 删除用户历史会话
 * @params
 */
export function fetchDeleteUserConversation(conversationIdList: string[]) {
  return http.post('/conversation/api/conversation/mobile/v1/delete_user_conversation', {
    conversationIdList,
  })
}

/**
 * 获取历史会话ID
 * @params
 */
export async function fetchSessionConversationId<T>(data: T) {
  const payload = (data || {}) as Record<string, any>

  // 首次进入时 `currentToolId` 可能还没被 `ChatEditor` 写入 sessionStorage。
  // 这里做一个极短轮询，避免第一次请求 `toolId/busiId` 读到空字符串。
  let sessionToolId = safeSessionStorageGetItem('currentToolId') || ''
  if (!sessionToolId) {
    const maxWaitMs = 600
    const intervalMs = 100
    const start = Date.now()
    while (Date.now() - start < maxWaitMs) {
      await new Promise(resolve => setTimeout(resolve, intervalMs))
      sessionToolId = safeSessionStorageGetItem('currentToolId') || ''
      if (sessionToolId) {
        break
      }
    }
  }

  const requestData = {
    ...payload,
    busiType: '01',
    busiId: sessionToolId,
    toolId: sessionToolId,
  }
  return http.post('/conversation/api/conversation/mobile/v1/get_user_conversation_session', requestData)
}
