<template>
  <v-card title="Delete a realm" class="min-h-[540px]" :loading="loading">
    <template #text>
      You are deleting a channel
      <b>{{ channels.related.delete_to?.name }}</b> <br />
      All messaging belonging to this channel 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="channels.show.delete = false">Not really</v-btn>
        <v-btn color="error" :disabled="loading" @click="deleteChannel">Yes</v-btn>
      </div>
    </template>
  </v-card>

  <v-snackbar v-model="success" :timeout="3000">The realm has been deleted.</v-snackbar>

  <!-- @vue-ignore -->
  <v-snackbar v-model="error" :timeout="5000">Something went wrong... {{ error }}</v-snackbar>
</template>

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

const route = useRoute()
const router = useRouter()
const channels = useChannels()

const emits = defineEmits(["relist"])

const error = ref<string | null>(null)
const success = ref(false)
const loading = ref(false)

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

  loading.value = true
  const res = await request("messaging", url, {
    method: "DELETE",
    headers: { Authorization: `Bearer ${await getAtk()}` }
  })
  if (res.status !== 200) {
    error.value = await res.text()
  } else {
    success.value = true
    channels.show.delete = false
    channels.related.delete_to = null
    emits("relist")
    if (route.name?.toString()?.includes("channel")) {
      await router.push({ name: "explore" })
    }
  }
  loading.value = false
}
</script>
