import { Document } from "mongoose";
import { IDraft } from "@models/stories/draft";
import { EventHandlerRequest, H3Event } from "h3";
import { IChapter } from "@models/stories/chapter";
import getDraftBucket from "@server/storyHelpers/getDraftBucket";
import { norm, stringifyStream } from "@functions";

export interface HydratedDraft extends Omit<IDraft, "chapters"> {
	chapters: (IChapter & { text: string })[];
}

export default async function (draft: Document<number, {}, IDraft> & IDraft, event: H3Event<EventHandlerRequest>): Promise<HydratedDraft> {
	const finObj = draft.toObject() as HydratedDraft;
	const bucket = getDraftBucket();
	for (let chap of finObj.chapters) {
		let dstream = bucket.openDownloadStreamByName(`/drafts/${chap.id}.txt`);
		chap.text = norm(await stringifyStream(dstream));
	}
	return finObj;
}
