export interface ActionRequestBody {
  args: Record<string, string>
  requestedBy: string
}

export interface ActionResponseBody {
  ok: boolean
  result?: unknown
  error?: string
}

/** Same-origin POST — proxied server-side by /api/collector/actions/:verb. */
export async function postCollectorAction(verb: string, body: ActionRequestBody): Promise<ActionResponseBody> {
  const res = await fetch(`/api/collector/actions/${encodeURIComponent(verb)}`, {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify(body),
  })
  const payload = await res.json().catch(() => ({})) as ActionResponseBody
  if (!res.ok) {
    throw new Error(
      typeof payload.error === 'string'
        ? payload.error
        : `action ${verb} failed: HTTP ${res.status}`,
    )
  }
  return payload
}
