<template>
  <v-card title="Delete a realm" class="min-h-[540px]" :loading="loading">
    <template #text>
      You are deleting a realm
      <b>{{ realms.related.delete_to?.name }}</b> <br />
      All posts belonging to this realm will be deleted and never appear again. Are you confirm?
    </template>
    <template #actions>
      <div class="w-full flex justify-end">
        <v-btn color="grey-darken-3" @click="realms.show.delete = false">Not really</v-btn>
        <v-btn color="error" :disabled="loading" @click="deleteRealm">Yes</v-btn>
      </div>
    </template>
  </v-card>
</template>

<script setup lang="ts">
import { request } from "@/scripts/request"
import { useRealms } from "@/stores/realms"
import { getAtk } from "@/stores/userinfo"
import { useRoute, useRouter } from "vue-router"
import { ref } from "vue"
import { useUI } from "@/stores/ui"

const { showSnackbar, showErrorSnackbar } = useUI()
const route = useRoute()
const router = useRouter()
const realms = useRealms()

const emits = defineEmits(["relist"])

const loading = ref(false)

async function deleteRealm() {
  const target = realms.related.delete_to
  const url = `/api/realms/${target.id}`

  loading.value = true
  const res = await request("interactive", url, {
    method: "DELETE",
    headers: { Authorization: `Bearer ${await getAtk()}` }
  })
  if (res.status !== 200) {
    showErrorSnackbar(await res.text())
  } else {
    showSnackbar("The realm has been deleted.")
    realms.show.delete = false
    realms.related.delete_to = null
    emits("relist")
    if (route.name?.toString()?.includes("realm")) {
      await router.push({ name: "explore" })
    }
  }
  loading.value = false
}
</script>
