import type { RequestRow } from './request-types'

export interface RequestAnswerResponse {
  request: RequestRow
  factory_delivery: 'not-applicable' | 'delivered' | 'gap'
}

export async function postRequestAnswer(id: string, answer: string): Promise<RequestAnswerResponse> {
  const response = await fetch(`/api/collector/requests/${encodeURIComponent(id)}/answer`, {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify({ answer }),
  })
  const body = await response.json().catch(() => null) as RequestAnswerResponse | { error?: string } | null
  if (!response.ok) throw new Error(body && typeof body === 'object' && 'error' in body ? String(body.error) : `HTTP ${response.status}`)
  return body as RequestAnswerResponse
}
