<template>
  <k-button
    v-if="pageStatus !== 'draft'"
    :theme="theme"
    variant="dimmed"
    :icon="icon"
    title="Rafraîchir le cache front"
    @click="refreshCache()"
    >{{ text }}</k-button
  >
</template>

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

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

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

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(() => {
      text.value = "Rafraîchir";
      icon.value = "refresh";
      theme.value = "aqua-icon";
    }, 2000);
  }
}
</script>
