import { Readable } from "stream";
import san from "sanitize-html";
import { FormStory } from "@client/types/form/story";
import isLoggedIn from "@server/middlewareButNotReally/isLoggedIn";
import { getBucket, bodyHandler, modelFormChapter } from "@server/storyHelpers";
import { Story } from "@models/stories";
import { sanitizeConf } from "@server/constants";
import { countWords } from "@functions";

export default eventHandler(async (ev) => {
	isLoggedIn(ev);
	const bucket = getBucket();
	const body = await readBody<FormStory>(ev);
	const story = new Story({
		title: body.title,
		author: ev.context.currentUser!._id,
		coAuthor: body.coAuthor,
		views: 0,
		reviews: 0,
		downloads: 0,
		ficmas: body.ficmas || null,
		challenge: body.challenge || null,
		completed: body.completed,
	});
	for (const c of body.chapters) {
		story.chapters.push(modelFormChapter(c));
		story.chapters[story.chapters.length - 1].words = countWords(
			await bodyHandler(c),
		);
	}
	await story.save();

	for (let i = 0; i < story.chapters.length; i++) {
		let c = story.chapters[i];
		const content = await bodyHandler(body.chapters[i]);
		const readable = new Readable();
		readable.push(content);
		readable.push(null);
		readable.pipe(bucket.openUploadStream(`/stories/${c.id}.txt`));
	}
	return {
		success: true,
		url: `/story/${story._id}/1`,
		story,
	};
});