import { seriesApi } from '@api/series';
import { storage } from 'src/storage';

const NAMESPACE = 'series';

function saveData<T>(key: string, data: T) {
  const namespacedKey = `${NAMESPACE}:${key}`;
  const jsonData = JSON.stringify(data);
  storage.set(namespacedKey, jsonData);
}

export async function saveSeriesRankingData() {
  const response = await seriesApi.getSeriesGroupsRanking();
  const groups = response.data.data;
  saveData('groups', groups);

  await Promise.all(
    groups.map(async (group) => {
      const response = await seriesApi.getSeriesRanking(group.id, 0, 50);
      saveData(`${group.id}`, response.data.data);

      if (group.series) {
        group.series.map(async (series) => {
          const subseries = await seriesApi.getSeriesRanking(series.id, 0, 50);
          saveData(`${series.id}`, subseries.data.data);
        });
      }
    })
  );
}
