<script setup>
definePageMeta({
  layout: 'admin'
})

const route = useRoute()
const id = computed(() => String(route.params.id || ''))
const saving = ref(false)
const deleting = ref(false)
const errorMessage = ref('')

const { data: post } = await useFetch(() => `/admin/api/posts/${id.value}`)

if (!post.value) {
  throw createError({
    statusCode: 404,
    statusMessage: '게시물을 찾을 수 없습니다.'
  })
}

/**
 * 게시물 수정 저장
 * @param {Object} payload - 게시물 입력값
 * @returns {Promise<void>} 저장 결과
 */
const savePost = async (payload) => {
  saving.value = true
  errorMessage.value = ''

  try {
    const updatedPost = await $fetch(`/admin/api/posts/${id.value}`, {
      method: 'PUT',
      body: payload
    })

    post.value = updatedPost
  } catch (error) {
    errorMessage.value = error?.data?.message || '글을 저장하지 못했습니다.'
  } finally {
    saving.value = false
  }
}

/**
 * 게시물 삭제
 * @returns {Promise<void>} 삭제 처리 결과
 */
const deletePost = async () => {
  if (!confirm(`"${post.value.title}" 글을 삭제할까요?`)) {
    return
  }

  deleting.value = true
  errorMessage.value = ''

  try {
    await $fetch(`/admin/api/posts/${id.value}`, {
      method: 'DELETE'
    })
    await navigateTo('/admin/posts')
  } catch (error) {
    errorMessage.value = error?.data?.message || '글을 삭제하지 못했습니다.'
  } finally {
    deleting.value = false
  }
}
</script>

<template>
  <section class="admin-post-edit bg-paper p-6">
    <div class="admin-post-edit__header mb-8 flex items-start justify-between gap-4">
      <div>
        <p class="admin-post-edit__eyebrow text-xs font-semibold uppercase text-muted">
          Posts
        </p>
        <h1 class="admin-post-edit__title mt-2 text-3xl font-semibold">
          글 수정
        </h1>
      </div>
      <div class="admin-post-edit__actions flex gap-2">
        <NuxtLink
          v-if="post.status === 'published'"
          class="admin-post-edit__view rounded border border-line bg-white px-4 py-2 text-sm font-semibold"
          :to="`/post/${post.slug}`"
          target="_blank"
        >
          보기
        </NuxtLink>
        <button
          class="admin-post-edit__delete rounded border border-red-200 bg-white px-4 py-2 text-sm font-semibold text-red-700 disabled:opacity-50"
          type="button"
          :disabled="deleting"
          @click="deletePost"
        >
          {{ deleting ? '삭제 중' : '삭제' }}
        </button>
      </div>
    </div>
    <p v-if="errorMessage" class="admin-post-edit__error mb-5 rounded border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
      {{ errorMessage }}
    </p>
    <AdminPostForm :initial-post="post" submit-label="변경 저장" :saving="saving" @submit="savePost" />
  </section>
</template>
