import { apiCms, cmsUrl } from './api';
import { CacheCmsContent } from '@/plugins/store/cache';

const getStaticUrl = (file) => `${cmsUrl}${file.url}`;

export const fetchListEcosystem = async (isCached = true) => {
  const CacheContent = new CacheCmsContent('ecosystem-list');

  const getCache = await CacheContent.get();

  if (isCached && getCache) {
    return getCache;
  }

  const listData = (await apiCms.get('/ecosystems')).map((item) => {
    return {
      ...item,
      logo: getStaticUrl(item.logo),
    };
  });

  if (isCached) {
    await CacheContent.set(listData);
  }

  return listData;
};

export const fetchExtensionInfo = async (isCached = true) => {
  const CacheContent = new CacheCmsContent('extension-info');

  const getCache = await CacheContent.get();

  if (isCached && getCache) {
    return getCache;
  }

  const data = await apiCms.get('/extension');

  data.logo = getStaticUrl(data.logo);

  if (isCached) {
    await CacheContent.set(data);
  }

  return data;
};

export const fetchPlatformConfig = async (isCached = true) => {
  const CacheContent = new CacheCmsContent('platform-config');

  const getCache = await CacheContent.get();

  if (isCached && getCache) {
    return getCache;
  }

  const data = await apiCms.get('/platform-config');

  if (isCached) {
    await CacheContent.set(data);
  }

  return data;
};
