import type { ChatMessage } from '@/types/db'

export type VoiceMessagePayload = {
  role: 'user' | 'assistant'
  content: string
  segment_id: string
  state_code?: string | null
  permit_id?: string | null
  answer_to_message_id: string | null
}

/** The final transcript is saved immediately; source lookup is separate. */
export async function saveVoiceMessage(tripId: string, payload: VoiceMessagePayload): Promise<ChatMessage> {
  const response = await fetch(`/api/trips/${tripId}/chat/voice-message`, {
      method: 'POST', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload), signal: AbortSignal.timeout(15_000),
  })
  const data = await response.json().catch(() => ({}))
  if (!response.ok || !data.message) throw new Error(data.error || 'Voice transcript could not be saved.')
  return data.message
}
