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

<script setup lang="ts">
import { ref, toRef, watch, onMounted } from 'vue'
import { assertSdkResponseOk } from '@/api/AssertSdkResponseOk'
import { ValidationError } from '@/api/errors'
import ClientSkeleton from '@/components/clients/ClientSkeleton.vue'
import ClientDetail from '@/components/clients/ClientDetail.vue'
import type { ClientCreate } from '@/client'
import { idKey } from '@/api/paths'
import { SshecretAdmin } from '@/client'
import { useTreeState } from '@/store/useTreeState'
import { useAlertsStore } from '@/store/useAlertsStore'

interface Props {
  id: string
  parentId?: string
}
const props = defineProps<Props>()
const clientId = toRef(() => props.id)
const client = ref<Client>()
const treeState = useTreeState()
const emit = defineEmits<{ (e: 'clientDeleted', data: string): void }>()
const alerts = useAlertsStore()

const updateErrors = ref([])

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

async function deleteClient(deleteId: string) {
  const response = await SshecretAdmin.deleteClientApiV1ClientsIdDelete({
    path: { id: idKey(deleteId) },
  })
  if (response.status !== 200) {
    console.error(response)
    return
  }

  emit('clientDeleted', deleteId)
}

function clearUpdateErrors() {
  updateErrors.value = []
}

async function updateClient(updated: ClientCreate) {
  const response = await SshecretAdmin.updateClientApiV1ClientsIdPut({
    path: { id: idKey(localClient.value.id) },
    body: data,
  })
  try {
    const responseData = assertSdkResponseOk(response)
    client.value = responseData
    clearUpdateErrors()
  } catch (err) {
    if (err instanceof ValidationError) {
      updateErrors.value = err.errors
    } else {
      const errorMessage = err.message ?? 'Unknown error'
      alerts.showAlert(`Error from backend: ${errorMessage}`, 'error')
    }
  }
}

onMounted(loadClient)

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