<template>
  <ClientDetail :client="client" @update="updateClient" @deleted="deleteClient" v-if="client" />
  <ClientSkeleton v-else />
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
import ClientSkeleton from '@/components/clients/ClientSkeleton.vue'
import ClientDetail from '@/components/clients/ClientDetail.vue'
import type { ClientCreate } from '@/client'
import { SshecretAdmin } from '@/client'
import { useTreeState } from '@/store/useTreeState'

const props = defineProps<{ clientId: string | null }>()

const client = ref<Client>()

const treeState = useTreeState()

async function loadClient() {
  if (!props.clientId) return
  client.value = await treeState.getClient()
}

async function deleteClient(clientId: string) {
  console.log(`Delete ${localClient.value.id}`)
  const response = await SshecretAdmin.deleteClientApiV1ClientsIdDelete({
    path: { id: clientId },
  })
  if (response.status !== 200) {
    console.error(response)
    return
  }

  emit('clientDeleted', clientId)
  props.clientId = null
}

async function updateClient(updated: ClientCreate) {
  const response = await SshecretAdmin.updateClientApiV1ClientsIdPut({
    path: { id: localClient.value.id },
    body: data,
  })
  client.value = response.data
}

onMounted(loadClient)

watch(
  () => props.client_id,
  () => loadClient(),
  { immediate: true },
)
</script>
