<script setup lang="ts">
import { computed } from 'vue'
import { useRoute } from 'vue-router'
import { useQuery } from '@tanstack/vue-query'
import { fetchSpec } from '@/api/specs'
import { usePostHog } from '@/composables/usePostHog'
import Breadcrumb from '@/components/layout/Breadcrumb.vue'
import SpecDetail from '@/components/spec/SpecDetail.vue'
import LoadingSpinner from '@/components/common/LoadingSpinner.vue'

const route = useRoute()
const { track } = usePostHog()

const org = computed(() => route.params.org as string)
const owner = computed(() => route.params.owner as string)
const repo = computed(() => route.params.repo as string)
const path = computed(() => route.params.path as string)

const { data, isLoading } = useQuery({
  queryKey: ['spec', org, owner, repo, path],
  queryFn: async () => {
    const result = await fetchSpec(org.value, owner.value, repo.value, path.value)
    track('spec_viewed', {
      repo: `${owner.value}/${repo.value}`,
      file_path: path.value,
      status: result.document.frontmatter.status,
    })
    return result
  },
})

const breadcrumbs = computed(() => [
  { label: 'Dashboard', to: `/app/${org.value}/` },
  { label: `${owner.value}/${repo.value}`, to: `/app/${org.value}/repos/${owner.value}/${repo.value}` },
  { label: data.value?.document.frontmatter.title || path.value },
])
</script>

<template>
  <Breadcrumb :items="breadcrumbs" />
  <LoadingSpinner v-if="isLoading" />
  <SpecDetail v-else-if="data" :spec="data" :org="org" />
</template>
