import { logger } from 'tachyon-logger';
import { CLIENT_ID } from 'mweb/common/config/twitchClientID';

export const BASE_URL = 'https://api.twitch.tv/kraken/';

const JSON = 'json';
export const TEXT = 'text';
type Formats = typeof JSON | typeof TEXT;

const TIMEOUT = 1500; // Implemented for node-fetch but not whatwg-fetch.
const HEADERS = {
  Accept: 'application/vnd.twitchtv.v3+json',
  'Client-Id': CLIENT_ID,
};

// TODO: Switch to URL library instead of string concatenation.
export async function fetchData<ResponseT>(
  url: string,
  headers: { [key: string]: string } = {},
  format: Formats = JSON,
): Promise<ResponseT> {
  const fetchOptions = {
    timeout: TIMEOUT,
    headers: {
      ...HEADERS,
      ...headers,
    },
  };
  const LOAD_TIMER_NAME = `REQUEST_DATA_FOR_URL ${url}`;
  logger.info(`Requesting data from ${url}`);
  console.time(LOAD_TIMER_NAME);
  const response = await fetch(url, fetchOptions);
  console.timeEnd(LOAD_TIMER_NAME);
  if (response.status < 200 || 299 < response.status) {
    logError(url, response);
    throw response;
  }
  switch (format) {
    case JSON:
      return response.json();
    case TEXT:
    default:
      return response.text() as any;
  }
}

async function logError(url: string, response: Response): Promise<void> {
  const details = await response.text();
  logger.error({
    message: 'Failed request in loadData',
    status: response.status,
    url,
    details,
  });
}
