import axios from 'axios';
import { setup } from 'axios-cache-adapter';

const baseURL = process.env.REACT_APP_API_BASE_URL;

export const cacheAPI = setup({
  baseURL,
  cache: {
    maxAge: 0
  }
});

export function getApi(withCache) {
  return withCache ? cacheAPI : axios;
}

export function getApiStore() {
  return Object.fromEntries(
    Object.entries(cacheAPI.cache.store).map(([key, value]) => [key, JSON.parse(value)])
  );
}

export function invalidateAllApiCaches() {
  cacheAPI.cache.store = {};
}

export function invalidateApiCache(fetchURL) {
  const key = `${baseURL}${fetchURL}`;
  const { [key]: _, ...validCaches } = cacheAPI.cache.store;
  cacheAPI.cache.store = validCaches;
}

export function updateApiCache(fetchURL, responseData) {
  const key = [`${baseURL}${fetchURL}`];
  if (key in cacheAPI.cache.store) {
    const oldData = JSON.parse(cacheAPI.cache.store[key]);
    cacheAPI.cache.store[key] = JSON.stringify({
      ...oldData,
      data: { ...oldData.data, data: responseData }
    });
  }
}
