import http from '@/utils/request'
import { normalizeToolIdForApi, 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
 * 制度活化：不传 toolId/busiId（空字符串）；工具模式：以 session 或入参为准。
 * 若入参显式包含 toolId 或 busiId（含空串），优先于 session，避免轮询把「默认第 0 个工具」误写入后再带上。
 */
export async function fetchSessionConversationId<T>(data: T) {
  const payload = (data || {}) as Record<string, any>
  const fromSession = normalizeToolIdForApi(safeSessionStorageGetItem('currentToolId'))

  const hasExplicitTool
    = Object.prototype.hasOwnProperty.call(payload, 'toolId')
      || Object.prototype.hasOwnProperty.call(payload, 'busiId')
  const explicitRaw = Object.prototype.hasOwnProperty.call(payload, 'toolId')
    ? payload.toolId
    : Object.prototype.hasOwnProperty.call(payload, 'busiId')
      ? payload.busiId
      : undefined

  const resolved = hasExplicitTool
    ? normalizeToolIdForApi(explicitRaw)
    : fromSession

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