<template>
  <div id="refresh-cache-button">
    <k-button
      v-if="pageStatus !== 'draft'"
      :theme="theme"
      variant="dimmed"
      :icon="icon"
      :title="title"
      @click="refreshCache()"
      >{{ 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 title = computed(() => {
  return lastCacheUpdate?.length > 0
    ? "Dernière mise à jour : " + lastCacheUpdate
    : "Mettre à jour le cache front";
});

async function refreshCache() {
  text.value = "En cours…";
  icon.value = "loader";
  theme.value = "orange-icon";

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

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

  if (json.status === "error") {
    console.error(json);
    text.value = "Erreur";
    icon.value = "alert";
    theme.value = "red-icon";
  } else {
    console.log(json);
    text.value = "Terminé";
    icon.value = "check";
    theme.value = "green-icon";

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