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();
  if (response && response.data) {
    const last30Dates = response.data.dates.slice(-30);
    saveData('dates', last30Dates);

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