<script setup lang="ts">
import { router } from '@/router'
import { onMounted, ref } from 'vue'
import { api } from '@/utils/axios.ts'
import type { PostDetail } from '@/models'
import PostDetailContent from '@/components/PostDetailContent.vue'

function parseId() {
  let targetPostId = router.currentRoute.value.params['id']
  if (Array.isArray(targetPostId)) {
    if (targetPostId.length) {
      targetPostId = targetPostId[0]
    } else return undefined
  }
  const id = Number(targetPostId)
  if (isNaN(id)) {
    return undefined
  }
  return id
}

let postId = NaN

const postDetail = ref<PostDetail | null>(null)

async function freshData() {
  const res = await api.postGet(postId)
  if (res.code == 200) {
    postDetail.value = res.data
    return true
  } else return false
}

onMounted(() => {
  postId = parseId() ?? NaN
  if (!postId) {
    router.push('/')
  }

  freshData().then((res) => {
    if (!res) router.push('/')
  })
})
</script>

<template>
  <PostDetailContent v-if="postDetail" :target="postDetail" />
</template>

<style scoped></style>
