function authHeaders() {
  return window.getAuthHeaders ? window.getAuthHeaders() : { 'Content-Type': 'application/json' };
}

function parseJsonWithStatus(response) {
  return response.json().catch(function () { return {}; }).then(function(data) {
    data._status = response.status;
    return data;
  });
}

export function fetchAssistantStatus() {
  return fetch('/api/clinical-assistant/status', { headers: authHeaders(), credentials: 'same-origin' })
    .then(function(r) { return r.json(); });
}

export function fetchAssistantExamples() {
  return fetch('/api/clinical-assistant/examples', { headers: authHeaders(), credentials: 'same-origin' })
    .then(function(r) { return r.json(); });
}

export function openAssistantStream(payload, options) {
  options = options || {};
  return fetch('/api/clinical-assistant/chat/stream', {
    method: 'POST',
    headers: authHeaders(),
    credentials: 'same-origin',
    signal: options.signal,
    body: JSON.stringify(payload)
  });
}

export function fetchAssistantChat(payload, options) {
  options = options || {};
  return fetch('/api/clinical-assistant/chat', {
    method: 'POST',
    headers: authHeaders(),
    credentials: 'same-origin',
    signal: options.signal,
    body: JSON.stringify(payload)
  }).then(parseJsonWithStatus);
}

export function requestAssistantImage(prompt) {
  return fetch('/api/clinical-assistant/image', {
    method: 'POST',
    headers: authHeaders(),
    credentials: 'same-origin',
    body: JSON.stringify({ prompt: prompt })
  }).then(function(r) { return r.json(); });
}

export function startAssistantImageJob(prompt) {
  return fetch('/api/clinical-assistant/image/jobs', {
    method: 'POST',
    headers: authHeaders(),
    credentials: 'same-origin',
    body: JSON.stringify({ prompt: prompt })
  }).then(function(r) { return r.json(); });
}

export function fetchAssistantImageJob(jobId) {
  return fetch('/api/clinical-assistant/image/jobs/' + encodeURIComponent(jobId), {
    headers: authHeaders(),
    credentials: 'same-origin'
  }).then(function(r) { return r.json(); });
}

export function saveAssistantChat(payload) {
  return fetch('/api/clinical-assistant/chats', {
    method: 'POST',
    headers: authHeaders(),
    credentials: 'same-origin',
    body: JSON.stringify(payload)
  }).then(parseJsonWithStatus);
}

export function fetchSavedAssistantChats() {
  return fetch('/api/clinical-assistant/chats', { headers: authHeaders(), credentials: 'same-origin' })
    .then(function(r) { return r.json(); });
}

export function fetchSavedAssistantChat(id) {
  return fetch('/api/clinical-assistant/chats/' + encodeURIComponent(id), { headers: authHeaders(), credentials: 'same-origin' })
    .then(parseJsonWithStatus);
}

export function deleteSavedAssistantChat(id) {
  return fetch('/api/clinical-assistant/chats/' + encodeURIComponent(id), {
    method: 'DELETE',
    headers: authHeaders(),
    credentials: 'same-origin'
  }).then(function(r) { return r.json(); });
}
