<template>
  <v-card title="Delete a message" class="min-h-[540px]" :loading="loading">
    <template #text>
      You are deleting a message
      <b>#{{ channels.related?.messages?.delete_to?.id }}</b> <br />
      This message will gone and never appear again. But the replies won't affected. Are you confirm?
    </template>
    <template #actions>
      <div class="w-full flex justify-end">
        <v-btn color="grey-darken-3" @click="channels.show.messages.delete = false">Not really</v-btn>
        <v-btn color="error" :disabled="loading" @click="deleteMessage">Yes</v-btn>
      </div>
    </template>
  </v-card>
</template>

<script setup lang="ts">
import { request } from "@/scripts/request"
import { getAtk } from "@/stores/userinfo"
import { useChannels } from "@/stores/channels"
import { ref } from "vue"
import { useUI } from "@/stores/ui"

const channels = useChannels()

const { showSnackbar, showErrorSnackbar } = useUI()
const loading = ref(false)

async function deleteMessage() {
  const target = channels.related.messages.delete_to
  const url = `/api/channels/${target.channel.alias}/messages/${target.id}`

  loading.value = true
  const res = await request("messaging", url, {
    method: "DELETE",
    headers: { Authorization: `Bearer ${await getAtk()}` }
  })
  if (res.status !== 200) {
    showErrorSnackbar(await res.text())
  } else {
    showSnackbar("The message has been deleted.")
    channels.show.messages.delete = false
    channels.related.messages.delete_to = null
  }
  loading.value = false
}
</script>
