import { apiRequest } from './api.js'

export function runOrchestrator(payload, options = {}) {
  return apiRequest('/orchestrator/run', {
    method: 'POST',
    body: JSON.stringify(payload),
    ...options
  })
}

export function fetchLatestConversation(userId, sessionType = '', options = {}) {
  const params = new URLSearchParams({
    user_id: String(userId || '').trim()
  })
  if (String(sessionType || '').trim()) {
    params.set('session_type', String(sessionType || '').trim())
  }
  if (options.preferRecoverable) {
    params.set('prefer_recoverable', 'true')
  }

  return apiRequest(`/orchestrator/conversations/latest?${params.toString()}`)
}

export function clearUserConversations(userId, sessionType = '') {
  const params = new URLSearchParams({
    user_id: String(userId || '').trim()
  })
  if (String(sessionType || '').trim()) {
    params.set('session_type', String(sessionType || '').trim())
  }

  return apiRequest(`/orchestrator/conversations?${params.toString()}`, {
    method: 'DELETE'
  })
}

export function deleteConversation(conversationId, userId) {
  const params = new URLSearchParams({
    user_id: String(userId || '').trim()
  })

  return apiRequest(`/orchestrator/conversations/${encodeURIComponent(String(conversationId || '').trim())}?${params.toString()}`, {
    method: 'DELETE'
  })
}
