<script setup>

import {useFunctions} from "~/composables/useFunctions.js";

const supabase = useSupabaseClient()
const profileStore = useProfileStore()
const router = useRouter()

const itemInfo = ref({})



const createTicket = async () => {

  const {data:ticketData,error:ticketError} = await supabase.from("tickets").insert({
    title: itemInfo.value.title,
    created_by: profileStore.activeProfile.id,
    tenant: profileStore.currentTenant
  }).select().single()

  if(ticketError) {
    console.error(ticketError)
  } else {
    console.log(ticketData)
    const {data:messageData,error:messageError} = await supabase.from("ticketmessages").insert({
      ticket: ticketData.id,
      profile: profileStore.activeProfile.id,
      content: itemInfo.value.content,
      internal: false
    })

    if(messageError) {
      console.log(messageError)
    } else {
      router.push(`/support/${ticketData.id}`)
      await useFunctions().useSendTelegramNotification(`Ticket von ${profileStore.activeProfile.fullName} erstellt : ${itemInfo.value.content}`)
    }
  }
}

</script>

<template>
  <UDashboardNavbar title="Neues Ticket erstellen">
    <template #right>
      <UButton
        @click="createTicket"
      >
        Erstellen
      </UButton>
    </template>
  </UDashboardNavbar>
  <UForm class="w-2/3 mx-auto mt-5">
    <UFormGroup
      label="Titel:"
    >
      <UInput
        v-model="itemInfo.title"
      />
    </UFormGroup>
    <UFormGroup
      label="Nachricht:"
    >
      <UTextarea
        v-model="itemInfo.content"
      />
    </UFormGroup>
  </UForm>
</template>

<style scoped>

</style>