import { triumphsApi } from '@api/triumphs';
import { storage } from 'src/storage';

const NAMESPACE = 'triumphs';

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

export async function saveTriumphsData() {
  const response = await triumphsApi.getDates();
  const last30Dates = response.data.dates.slice(-30);
  saveData('dates', last30Dates);

  await Promise.all(
    last30Dates.map(async (date) => {
      const response = await triumphsApi.getData(date);
      saveData(`data_${date}`, response.data.triumphs);
    })
  );
}
