<script lang="ts" setup>
	import { v4 } from "uuid";
	import storyForm from "~/components/story/create/storyform.vue";
	import { FormStory } from "~/lib/client/types/form/story";
	import { IStory } from "~/models/stories";
	import { IChapter } from "~/models/stories/chapter";
	const rtr = useRoute();
	const {
		data: { value: originalStory },
	} = await useApiFetch<{ chapters: (IChapter & { text: string })[] } & IStory>(
		`/story/${rtr.params.id}/full`,
	);
	if (!originalStory) {
		await navigateTo("/not-found");
	}
	definePageMeta({
		middleware: [
			(from, to) => {
				const { data: curu } = useAuth();
				if (
					curu.value?.user?._id !== originalStory?.author._id &&
					curu.value?.user?._id !== originalStory?.coAuthor._id
				) {
					return navigateTo("/403");
				}
			},
		],
	});
	const story: FormStory = {
		title: originalStory!.title,
		coAuthor: originalStory?.coAuthor._id,
		completed: originalStory!.completed,
		chapters: originalStory!.chapters.map((a, i) => ({
			id: a.id,
			chapterTitle: a.title,
			index: i + 1,
			summary: a.summary,
			notes: a.notes,
			genre: a.genre,
			bands: a.bands.map((a) => a._id),
			characters: a.characters,
			relationships: a.relationships,
			nsfw: a.nsfw,
			loggedInOnly: a.loggedInOnly,
			hidden: a.hidden,
			content: a.text,
			uuidKey: v4(),
		})),
	};
</script>
<template>
	<a-typography-title style="text-align: center">
		Editing "{{ originalStory!.title }}"
	</a-typography-title>
	<story-form
		:can-draft="false"
		:data="story"
		:endpoint="`/story/${rtr.params.id}`"
		endpoint-method="put"
	>
	</story-form>
</template>
