<script lang="ts" setup>
	import { v4 } from "uuid";
	import storyForm from "~/components/story/create/storyform.vue";
	import { FormStory } from "@client/types/form/story";
	import { IStory } from "@models/stories";
	import { IChapter } from "@models/stories/chapter";

	import { storyEditMiddleware } from "@client/middleware";
	import { IBand } from "@models/band";
	import { IUser } from "@models/user";
	const rtr = useRoute();
	const {
		data: { value: originalStory },
	} = await useApiFetch<({ chapters: (IChapter & { text: string })[] } & IStory) | null>(`/story/${rtr.params.id}/full`);
	if (originalStory === null) {
		console.log("IT DOESN'T EXIST DAWG");
		throw createError({
			statusCode: 404,
			message: "That story doesn't exist...",
		});
	}
	definePageMeta({
		middleware: ["auth", storyEditMiddleware],
	});
	const story: FormStory = {
		title: originalStory!.title,
		coAuthor: originalStory?.coAuthor ? (originalStory.coAuthor as IUser)._id : null,
		completed: originalStory!.completed,
		chapters: originalStory!.chapters.map((a, i) => ({
			...a,
			id: a.id,
			chapterTitle: a.title,
			index: i + 1,
			bands: (a.bands as IBand[]).map((a) => a._id),
			content: a.text,
			uuidKey: v4(),
		})),
	};
	useHead({
		title: `Editing story: ${originalStory?.title}`,
	});
</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>
