<script setup lang="ts">
import { fetchWithCache } from '~/utils/cacheUtil';
import { progressTypeToDictionary } from '~/utils/convertProgressTypeToDictionary';

const data = ref<ProgressType | null>(null);
const loading = ref<boolean>(true);
const error = ref<string | null>(null);
let dict = ref<ProgressDictionary[] | null>(null);

const fetchMyData = async () => {
    try {
        loading.value = true;

        // Use the caching utility
        data.value = await fetchWithCache<ProgressType>(
              'Progress',
              async () => {
                const response = await fetch('https://proxy.rbwr.dk/progress');
                if (!response.ok) throw new Error('API fetch failed');
                return (await response.json()) as ProgressType;
            },
            5 // Cache max age in seconds
        );

    } catch (err) {
        error.value = (err as Error).message;
    } finally {
        loading.value = false;

      if (data.value !== null) {
        dict.value = progressTypeToDictionary(data.value);
      }
    }
};

fetchMyData();

</script>

<template>
  <div class="h-screen grid place-items-center">
    <div v-if="dict">
      <table class="table-auto border-gray-300">
        <thead>
          <tr>
            <th class="px-4 py-2">Metric</th>
            <th class="px-4 py-2">Value</th>
          </tr>
        </thead>

        <tbody>
          <tr v-for="d in dict">
            <td class="px-4 py-2">{{d.description}}</td>
            <td class="px-4 py-2">{{d.value}}</td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<style scoped>

</style>