<template>
  <div id="refresh-cache-button">
    <k-button
      v-if="pageStatus !== 'draft'"
      :theme="theme"
      variant="dimmed"
      :icon="icon"
      :title="title"
      @click="refreshCache()"
      :disabled="isProcessing"
      >{{ text }}</k-button
    >
  </div>
</template>

<script setup>
import { computed, ref } from "vue";

const { pageUri, pageStatus, lastCacheUpdate } = defineProps({
  pageUri: String,
  pageStatus: String,
  lastCacheUpdate: String,
});

const text = ref("Rafraîchir");
const icon = ref("refresh");
const theme = ref("aqua-icon");
const isProcessing = ref(false);

const title = computed(() => {
  return lastCacheUpdate?.length > 0
    ? "Dernière mise à jour : " + lastCacheUpdate
    : "Mettre à jour le cache front";
});

async function refreshCache() {
  isProcessing.value = true;
  icon.value = "loader";
  theme.value = "orange-icon";

  // Pour les projets multiples (batch processing)
  if (pageUri === 'projects') {
    await refreshAllProjects();
  } else {
    await refreshSingleProject();
  }
}

async function refreshAllProjects() {
  let offset = 0;
  const limit = 10; // 10 projets par batch
  let hasMore = true;
  let total = 0;

  text.value = "En cours 0%";

  try {
    while (hasMore) {
      const init = {
        method: "POST",
        "Content-Type": "application/json",
        body: JSON.stringify({
          pageUri: 'projects',
          offset,
          limit
        }),
      };

      const res = await fetch("/refresh-cache.json", init);
      const json = await res.json();

      if (json.status === "error") {
        throw new Error(json.message);
      }

      total = json.total;
      hasMore = json.hasMore;
      offset = json.nextOffset;

      // Mise à jour de la progression dans le texte du bouton
      const progress = Math.round((json.processed / json.total) * 100);
      text.value = `En cours ${progress}%`;

      console.log(`Batch terminé : ${json.processed}/${json.total} projets (${progress}%)`);
    }

    // Succès
    text.value = "Terminé";
    icon.value = "check";
    theme.value = "green-icon";

    setTimeout(() => {
      location.href = location.href;
    }, 2000);

  } catch (error) {
    console.error(error);
    text.value = "Erreur";
    icon.value = "alert";
    theme.value = "red-icon";
    isProcessing.value = false;
  }
}

async function refreshSingleProject() {
  text.value = "En cours…";

  const init = {
    method: "POST",
    "Content-Type": "application/json",
    body: JSON.stringify({ pageUri }),
  };

  try {
    const res = await fetch("/refresh-cache.json", init);
    const json = await res.json();

    if (json.status === "error") {
      throw new Error(json.message);
    }

    console.log(json);
    text.value = "Terminé";
    icon.value = "check";
    theme.value = "green-icon";

    setTimeout(() => {
      location.href = location.href;
    }, 1500);

  } catch (error) {
    console.error(error);
    text.value = "Erreur";
    icon.value = "alert";
    theme.value = "red-icon";
    isProcessing.value = false;
  }
}
</script>
