import { error } from '@sveltejs/kit';

/**
 * Returns the specified response object's body as an object if the status is ok.
 * If not, raises an error after attempting to extract a detailed
 * error message from the response body.
 * @param {Response} response - The response to inspect
 * @throws {Error} With a detailed Error.message if the response's status is not ok.
 * @returns {unknown} The object contained by the response object
 */
export async function getResponseBodyOrError(response: Response): Promise<unknown> {
  const json = await response.json();

  if (!response.ok) {
    if ('detail' in json) {
      if (typeof json.detail === 'string') {
        throw error(response.status, json.detail);
      } else if (Array.isArray(json.detail)) {
        if ('msg' in json.detail[0] && typeof json.detail[0].msg === 'string') {
          throw error(response.status, json.detail[0].msg);
        }
      }
    }
    throw error(response.status, `API request failed: ${response.statusText}`);
  }
  return json;
}
