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();
  if (response && response.data) {
    const groups = response?.data?.data;
    groups && saveData('groups', groups);
    if (!groups) return;

    await Promise.all(
      groups.map(async (group) => {
        const res = await seriesApi.getSeriesRanking(group.id, 0, 50);
        res?.data?.data && saveData(`${group.id}`, res.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);
          });
        }
      })
    );
  }
}
