import appConfig from '../config/appConfig.json';
import errors from '../config/errors.js';

import { getAuthState } from '../realm/actions/AuthActions';

export function fetchAuth(endpoint, body) {
  const request = {
    method: endpoint.method,
    headers: {
      Authorization: appConfig.appSecret,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(body)
  };

  return fetch(endpoint.url, request).then(res => res.json()).catch(() => ({ error: errors.APP_NETWORK_ERROR }));
}


// Fetch wrapper for authorized calls with valid session id. Returns either a JSON object documented in the wiki or an error.
export async function fetchTagferApi(endpoint, body) {
  const sessionId = await getAuthState();

  const request = {
    method: endpoint.method,
    headers: {
      Authorization: sessionId,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(body)
  };

  return fetch(endpoint.url, request).then(res => res.json()).catch(() => ({ error: errors.APP_NETWORK_ERROR }));
}
