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

const saving = ref(false)
const errorMessage = ref('')
const postForm = ref(null)

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

  try {
    const post = await $fetch('/admin/api/posts', {
      method: 'POST',
      body: payload
    })

    postForm.value?.clearAutosave()
    await navigateTo(`/admin/posts/${post.id}`)
  } catch (error) {
    errorMessage.value = error?.data?.message || '글을 저장하지 못했습니다.'
  } finally {
    saving.value = false
  }
}
</script>

<template>
  <section class="admin-post-editor bg-paper p-6">
    <div class="admin-post-editor__header mb-8">
      <p class="admin-post-editor__eyebrow text-xs font-semibold uppercase text-muted">
        Posts
      </p>
      <h1 class="admin-post-editor__title mt-2 text-3xl font-semibold">
        새 글 작성
      </h1>
    </div>
    <p v-if="errorMessage" class="admin-post-editor__error mb-5 rounded border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
      {{ errorMessage }}
    </p>
    <AdminPostForm ref="postForm" submit-label="글 저장" :saving="saving" @submit="savePost" />
  </section>
</template>
